简体   繁体   中英

SQL Insert value from array

So I am working on some code that inserts a piece of text and an id into a table. I send the code the text and the user's name. I want to take the username, and select the id that corresponds to it from the users table. I then insert that into the text table.

I have tried this:

$id = mysql_query("SELECT users.id FROM users WHERE name='$username'");

mysql_query("INSERT INTO `shouts` (`id`, `user`, `text`, `datetime`) VALUES (NULL, '$id', '$text', '$datetime');");

But it does not work, because the variable $id holds sql data. How can i turn that data into and integer?

From the manual :

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Also from the manual:

Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.

To answer your question, try this:

$id = mysql_query("SELECT users.id FROM users WHERE name='$username'");
$id = mysql_fetch_assoc($id);
mysql_query("INSERT INTO `shouts` (`id`, `user`, `text`, `datetime`) VALUES (NULL, '". $id['id']."', '$text', '$datetime');");

Although this is a Bad Idea™ and you should really look into using PDO . It's really not that hard. It will provide you with the ability to prepare your SQL statements, making you really be able to sleep easier at night knowing that you're not going to be a victim of SQL injection. The code you have is ambiguous at best whether or not you already are a victim yourself.

try $id = addslashes($id); or any other method of encoding the sql string

$id

is going to contain your results you need to get the id and put that into a variable. Check out the mysql_fetch_row function I think that will get you what you want. mysql_fetch_row syntax

mysql_query never returns a normal variable, only a result resource. Try mysql_fetch_assoc to get the data out of the select query. Also, the MySQL php extension is deprecated and you are encouraged to move to MySQLi or PDO.

this should work

   $sql = mysql_query("SELECT users.id FROM users WHERE name='$username'");
    $id = mysql_fetch_array($sql)['id'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM