Jump to content

using variables as part of INSERT statement


Takson

Recommended Posts

I am new to PHP and am currently learning the ropes.  I have writen some code to insert a line into a mySQL database.  I have created 3 fields in the mySQL database and am passing values two them.  I can use a declared variable to pass information to the filed ID (Index filed in mySQL) but if I use a variable to pass purely text values the database is not updated. 

 

mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ($category, $internalId, $category2)" );

 

If I replace the variables with specific text, the rows are added successfully.

 

mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ('werwerwer', $internalId, 'werrr')" );

 

 

It must be something stupid, I am sure.  Full code below

 

 

 

 

ob_start();

$host="localhost:8888"; // Host name

$username=""; // Mysql username

$password=""; // Mysql password

$db_name="expenses"; // Database name

$tbl_name="expense_category"; // Table name

$category="test3";

$internalId="7";

$category2="test3";

 

// Connect to server and select databse.

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

 

mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ('werwerwer', $internalId, 'werrr')" );

 

    echo "Done now 6!";

 

 

 

?>

When you put string data in an SQL statement, it has to have quotes around it.

 

You put quotes around the literals here:

mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) 
VALUES ('werwerwer', $internalId, 'werrr')" );

 

You have to do it here as well:

mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) 
VALUES ('$category', $internalId, '$category2')" );

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.