tdrsam tdrsam - 4 months ago 7
MySQL Question

PHP MySQL Selecting data from DB column

I have a php file that inserts data to a table with this line:

$insert_1 = mysql_query("INSERT INTO table_1 (`column_2`, `column_3`) VALUES ('value_2','value_3')");


Column_1 in table_1 is the id column which is an auto_increment column. Then, I copy the id column from table_1 to table_2 with this line:

$insert_2 = mysql_query("INSERT INTO table_2 (`id`) SELECT id FROM table_1 WHERE column_1 = ('value_1')");


Then, I'm trying to add the value in the id column to a session variable using this:

if ($insert_2) {
$select = mysql_query("SELECT `id` from `table_1` WHERE `column_2` = 'value_2'");
session_start();
$_SESSION["Register"] = $select;
}


But when I run a var_export I'm getting a null value for $select. All these variables come from form inputs and this code has been modified to be generic. But I can't figure out why the select variable would be null. The data I'm trying to get from the database exists, but it's not being stored in the variable I want (the $select variable). I just want the id stored in a variable and to pass that to the session.

Answer

mysql_query does not return the value you want. mysql_query return a mysql query result resource, to extract the data you need to use mysql_fetch_array (or assoc or other methods):

if ($insert_2) {
$select = mysql_query("SELECT `id` from `table_1` WHERE `column_2` = 'value_2'");
$myvalue = mysql_fetch_array($select);
session_start();
$_SESSION["Register"] = $myvalue[0];
}

Also, mysql stuff is deprecating, look at mysqli...

Comments