slwr
slwr

Reputation: 1175

MySQL - Get a value from column through ID in PHP

I have a database with the following structure:

id  msg
1  'Hello'
2  'Bye'

and I need to get "msg" value for the "id".

This is my try:

$text = mysql_query("SELECT msg FROM text WHERE text (id) ='$msg_num'");

But it doesn't work :( Do you have suggestions? Thanks

Upvotes: 3

Views: 29363

Answers (5)

cerealy
cerealy

Reputation: 122

select id from text where id = '$msg_num'

The difference in this query is that it selects the column. There are no column named 'msg', thats the value.

edit: Sorry, read the table wrong (sideways).

Upvotes: 2

John Woo
John Woo

Reputation: 263683

remove text

$result = mysql_query("SELECT msg FROM text WHERE id ='$msg_num'");
while ($row = mysql_fetch_array($result)) 
{
    $text = $row['msg'];  
}

your code is vulnerable with SQL Injection Please read the article below,

How can I prevent SQL injection in PHP?

Upvotes: 9

GBD
GBD

Reputation: 15981

Change

mysql_query("SELECT msg FROM text WHERE text (id) ='$msg_num'");

To

mysql_query("SELECT msg FROM text WHERE id ='$msg_num'");

This type of query can be cause of MySQL Injection attacks.. so good to use to stop for 1st order injection using prepared statements.

1) Mysqli

2) PDO

Upvotes: 3

nickhar
nickhar

Reputation: 20813

$text = mysql_query("SELECT msg FROM text WHERE id ='$msg_num'") or die(mysql_error());

Upvotes: 1

nyson
nyson

Reputation: 1055

Bad syntax.

$text = mysql_query("SELECT msg FROM text WHERE text (id) ='$msg_num'");

Should be:

$text = mysql_query("SELECT msg FROM text WHERE id='$msg_num'");

You can use mysql_error() to diagnose things like this.

Upvotes: 1

Related Questions