Help - Search - Members - Calendar
Full Version: Mysql Insert With Php
Zymic Webmaster Forums > Web Design & Development > Server Side Scripting > PHP
kevin_k
Hi Everybody:

I'm trying to use PHP to INSERT data into a valid MySQL table. Here's my query string:

CODE
$sql = "INSERT INTO comic
VALUES ('NULL', '$name[$loop]', '$release')";


What am I doing wrong?

EDIT: Well, just to be safe, I changed $name[$loop] with a temporary variable $nametmp as well as checked my table -- table name had been created with an older version of my table creation code and the name had been set to an older value. Once fiixed, it worked like a charm - double checked with PHPMyAdmin, the data was written successfully... Just one of those days I guess.
Ed
Well to have that work, you need to wrap it in braces; however, interpolated strings are not a good practice.

To get your string working:

CODE
$sql = "INSERT INTO `comic` VALUES(NULL, '{$name[$loop]}', '$release');";


This is more optimised written as:

CODE
$sql = 'INSERT INTO `comic` VALUES(NULL, \'' . $name[$loop] . '\', \'' . $release . '\')';


Reasons to why, can be found here:
http://blog.libssh2.org/index.php?/archive...-of-string.html
NDBoost
QUOTE(Bread @ Jul 15 2009, 11:15 PM) *
Well to have that work, you need to wrap it in braces; however, interpolated strings are not a good practice.

To get your string working:

CODE
$sql = "INSERT INTO `comic` VALUES(NULL, '{$name[$loop]}', '$release');";


This is more optimised written as:

CODE
$sql = 'INSERT INTO `comic` VALUES(NULL, \'' . $name[$loop] . '\', \'' . $release . '\')';


Reasons to why, can be found here:
http://blog.libssh2.org/index.php?/archive...-of-string.html

I should add that your values MUST be listed in the order of the columns within the table. IE: you couldn't have the values above listed backwards and expect them to work. The long hand version of this is something like, keep in mind use the same structure that Bread listed above:
CODE
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)


This way you can define the order of columns and you know the data is being placed in the right spot!

And don't forget to sanitize & check your data. I'm surprised Bread didn't say it yet, seeing as he's mr. sanitary hunter.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.