So I'm using a little script on php for a webpage adminisitration, and I get to do an item registration, so I get all my params and send them to the script to build an INSERT for the database (mysql). Here's my piece of code:
//Getting the params
$title = $_POST["title"];
$date = $_POST["date"];
$hour = $_POST["hour"];
$description = $_POST["description"];
$link = $_POST["link"];
$speaker = $_POST["speaker"];
$site = $_POST["site"];
$file = $_POST["file"];
//Link and File are optional, so I'll be using NULL instead if they're empty
$link = !empty($link) ? ("'".$link."'") : ("'". NULL ."'");
$file = !empty($file) ? ("'".$file."'") : ("'". NULL ."'");
//Now I'm ready to build the query
$query = "INSERT INTO ".$type;
$query = $query . "(title,data,hour,description,link,speaker,site,file)";
$query = $query . "VALUES (";
$query = $query . "'" .$title."'";
$query = $query . ",'".$date."'";
$query = $query . ",'".$hour."'";
$query = $query . ",'".$description."'";
$query = $query . ",".$link;
$query = $query . ",'".$speaker."'";
$query = $query . ",'".$site."'";
$query = $query . ",".$file.")";
//Finally, I'll be sending the INSERT as a query using:
$result = mysql_query($query);
if(!$result)
echo "SQL Error"
And so, I'm always getting inside the error statment. I've others INSERTS in other scripts on the same webpage, and they work well, this one mimics them. I've checked:
- mysql_connect() and mysql_select_db() are ok
- Database user I use has GRANTS to do the INSERT
- Database connectivity (checked using a SELECT query)
Any hint will be appreciated.
[SOLVED] Strings were not escaped, so the quotes were breaking the query. So if you're still issuing this kind of trouble and using the deprecated mysql _ API, you may as well need for the mysql_escape_string method (check Escaping single quote in PHP when inserting into MySQL ).