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!";

 

 

 

?>

Link to comment
Share on other sites

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')" );

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.