PHP MySQL INSERT statement syntax error - php

I'm having problems with an INSERT statement, and the error only says:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!

First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.

Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.

You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)

first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...

Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)

Related

Column count doesn't match value count at row 1 (columns and values are equal)

I'm getting the error: Column count doesn't match value count at row 1
I think, normally this error occurs if the count of the columns and the values aren't equal, but in my code they are...(3).
This is my php code:
$tempsongtitel = $_POST['songtitle'];
$tempinterpret = $_POST['interpret'];
$templink = $_POST['link'];
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel, $tempinterpret, $templink')") or die(mysql_error());
You missed some quotes. Should be:
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link) values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
Otherwise, you were trying to insert all three POST values into the first field.
Moreover, the mysql_ extension has been deprecated and is on the way out and is highly discouraged, especially if you are creating new software.
AND I'll presume you are first sanitizing your data? You're not really taking user input and placing it directly into the database, are you? Even if you don't do any data validation, you should escape your data in the query... easiest and most foolproof way to do that is by using parameterized queries.
The root cause is that your values are all in one set of quotes instead of quoted individually. I think this is a pretty common error, and in my experience it is an easy mistake to make, but not immediately obvious when scanning over your code. You can fix it like this (quick fix, still using deprecated mysql, but with post values escaped):
$tempsongtitel = mysql_escape_string($_POST['songtitle']);
$tempinterpret = mysql_escape_string($_POST['interpret']);
$templink = mysql_escape_string($_POST['link']);
$query = mysql_query("insert into tMusic (Songtitel, Interpret, Link)
values ('$tempsongtitel', '$tempinterpret', '$templink')") or die(mysql_error());
If you can, it would be much better to update your code to use PDO. You could use a prepared statement like this:
$stmt = $pdo->prepare("INSERT INTO tMusic (Songtitel, Interpret, Link) VALUES (?, ?, ?)");
$stmt->bindValue(1, $tempsongtitel);
$stmt->bindValue(2, $tempinterpret);
$stmt->bindValue(3, $templink);
$stmt->execute();
Among the many benefits of using this database extension rather than the old mysql functions it should not be possible to make an error like this in your code. In the prepared statement, there are no quotes around the parameter markers, so if you have VALUES ('?, ?, ?'), or even VALUES ('?', '?', '?') You would get bind errors when trying to bind the values, and the problem would become apparent pretty quickly.
I've found that, even though it's not 100% necessary and it's more time consuming, properly quoting and backticking EVERYTHING helps prevent this from happening.
$myQuery = "INSERT INTO `tMusic` (
`Songtitel`,
`Interpret`,
`Link`
) VALUES (
'$tempsongtitel',
'$tempinterpret',
'$templink'
);";
$runQuery = mysqi_query($DBi, $myQuery) or die(mysqli_error($DBi));
The formatting you use is up to you but this helps me make sure I have a one to one relationship and that I've quoted everything.
Of course that's using mysqli_* in place of the deprecated mysql_* functions AND that's assuming you've set $tempsongtitel, $tempinterpret and $templink properly.

PHP & SQL inserting into a database table error

I'm slowly progressing through PHP and SQL and have stumbled upon a small error, when trying to send a string into an SQL database. What I'm trying to do is insert a users's detail into one table (which currently works) and send the user name along with 5 blank entries into another table. The table examscore fields are username, exam, exam1, exam2, exam3, exam4 (it is these exam fields that I require blank for now).
The problem is that I receive the following message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\E-LearningWebsite\addcustomertodb.php on line 11 (which line that starts $query1)
If possible could anyone explain what this error means and what i have done wrong?
<?php
require "dbconn.php";
$username = $_GET['username'];
$email = $_GET['email'];
$pass = $_GET['password'];
$query = "INSERT INTO customer VALUES ('".$username."','".$email."','".$pass."')";
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
$results = mysql_query($query) or die (mysql_error());
$results1 = mysql_query($query1) or die (mysql_error());
?>
Kind regards Andy
change
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
to
$query1 = "INSERT INTO examscores VALUES ('".$username."','','','','','')";
ps. you are inviting SQL injections but that is a different story...
The goggles! They do nothing! The sql injection vulnerabilities! And it's only Monday!
Why not just
$query ="INSERT INTO customer VALUES ('$username', '$email', '$pass');";
$query1 = "INSERT INTO examscores VALUES ('$username', '', '', '', etc...);";
PHP will happily replace $vars inside "" quoted strings for you. There's absolutely not need for all the concatentation you're doing. Any decent code editor will still highlight the vars for you.
you are missing dots to concatenate your strings
$query1 = "INSERT INTO examscores VALUES ('".$username."','"."','"."','"."','"."','"."')";
furthermore you dont need to have different strings
and still further more you dont need to include every column if you are not inserting them
Your immediate problem causing the errors is the missing .s from query1 from between the double-doublequotes, (or you should just delete the double-doublequotes altogether. Or even the unneeded columns...).
But there are way bigger issues in your code:
SQL injection: your code is vulnerable. You should at least escape th variables coming from the user...
mysql_* deprecation: as of PHP 5.5, these functions will be deprecated. Use either Mysqli or even ebtter PDO.

PHP MySQL INSERT not inserting nor any error is displayed

I have got this code so insert values into a table in MySQL through PHP. I have tried all the possible Insert syntax, it does not insert the data... this are the codes that i used.
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
I even tried the following sql syntax
"INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param1','$param1')";
"INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('$param1','$param1')";
and i tried several other none of them inserts anything into the table. and this is the table in MySQL;
trail
User_Name varchar(35)
Quiz_ID varchar(35)
It does not insert anything nor does it display any error. And I have the correct DB connection because i am able to Select from the table. Its just the insert that is tricky.
Any help would be much appreciated.
Thanks
Just a note if someone is running on similar problems:
I had a similar issue --- Insert query working on PHPMyAdmin but not working on PHP and not issuing any errors (result was true all the time).
The reason is that I was starting a transaction but forgetting to commit it...
$mysqli->autocommit(FALSE);
$mysqli->query( "START TRANSACTION" );
Never forget this:
$mysqli->commit();
It is a silly error, I know, but I was so focused on the query mistery that I forgot the transaction statements a few lines above.
Check the mysqli::$errno first.
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
What I have done is if you don't have a debugger installed, just have it email you the query. This way you can see what the final query is and if you have access to something like phpMyAdmin try manually running the query and see what happens. Another thing, make sure that you are searching for your inserted record correctly, if you are using a search query because of the number of records make sure the WHERE condition is right, that has burned me a few times.
EDIT
Missing symbol around names maybe. I have to run all my MySQL queries like
`nameOfThing`
instead of just nameOfThing
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
FYI, you are inserting $param1 twice.
You also don't have a ';' after echo "successful".
I'd suggest you clean up the code example, and try things again, and let us know.
Things to clean up
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param','$param1')";
You don't need to concatenate the variables in a string concatenate, you can interpolate. However, you actually should use PDO with a prepared statement to avoid the potential for SQL injection.
Add that missing ;
put that first check of if(mysql->errno==0) in (unless you are going to switch to PDO for this stuff).
Fix mysql->error to be mysql->error()
Maybe some other things from the comments.
Well, if the following code produce no error and shows 1 affected row, most likely you are looking for the result in the wrong database.
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('testing','1')";
$mysql->query($sql);
var_dump($mysql->error,$mysql->affected_rows);
My tables were InnoDB tables and when i changed my tables to MyISAM the insert worked fine. Well i have never encountered this problem before. Well that did the trick for the time being.
If i want to use InnoDB engine for transactions? How can i get php to be able to insert values in InnoDB table? Any one got any suggestion? And i am using WAMP server and the MySQL is version 5.5.24. And i did change the InnoDB conf in my.ini but that did not seem to work either?
try this
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')"; $result = $mysql_query($sql); if($result){ echo "successful";} else { echo " not successful;}

PHP Mysql multiple insert with foreach not working

Here is my code - I'm attempting to attach a bunch of user_id 's to a piece of content.
if (empty($errors)) // If everything's OK.
{
foreach($_POST['userId'] as $row)
{
$query = " ('".$row[learner_id]."', '".$postId."', '".$id."' ),";
}
$query = substr_replace($query,"",-1);
$mysql_return = mysqli_query("INSERT INTO subs (userId, postId, account_id ) VALUES ".$query) or die(mysql_error());
}
Would love any help you could give - it's not working...
And how's it not working? Syntax error? Silently puking? You're not escaping your POST data, so if any of those contain at least one single quote, that'll cause a syntax error right there, plus leaving you wide open for sql injection attacks.
Or maybe a foreign key check is failing... many possibilities, but you haven't given us nearly enough info to tell. What error message(s) are you getting?
Ok, I see several issues:
You are not using parameters or escaping, opening yourself up WIDE to sql injection attacks. See mysqli_real_escape_string.
What are you possibly sending to $_POST['userId'] that would make itself an array?
Unless learner_id is a constant, then this is a syntax error. If it is an array key, put it in quotes.
Where are $postId and $id coming from ?
The first parameter to mysqli_query is the identifier returned by mysqli_connect, whereas you're just giving it the query directly.
It should be like this,
$link = mysqli_connect("host", "user", "pass", "db");
$mysql_return = mysqli_query($link, "INSERT INTO subs (userId, postId, ac...

Mysql + php with special characters like '(Apostrophe) and " (Quotation mark)

I have been struggling with a small problem for a while. It's been there for years but it's just been an irritating problem and not a serious one, and I have just worked around it. But now I want to find out if anyone can help me. I have done some google'ing but no success.
If I do a form post from a html textarea in a php file like this:
<form action="http://action.com" method="post">
<textarea name="text">google's site</textarea>
</form>
and of course there is a submit button and so on.
The value is the problem: google's site The value of the textarea have both "(Quotation mark) and '(Apostrophe).
To save this in a mysql_database I do this:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".$_POST['text']."') ") or die(mysql_error());
And now I get the mysql error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's site'' at line 1
Your sql string will be:
INSERT INTO `table` (`row1`) VALUES ('google's site')
Which is not a valid statement. As Nanne wrote, escape the string at least with mysql_real_escape_string : http://php.net/manual/en/function.mysql-real-escape-string.php
And read about sql injection
http://en.wikipedia.org/wiki/SQL_injection
Think a bit: if someone posts this: $_POST['text'] with value: ');delete from table;....
Your can say good bye to your data :)
Always filter/escape input!
EDIT: As of PHP 5.5.0 mysql_real_escape_string and the mysql extension are deprecated. Please use mysqli extension and mysqli::escape_string function instead
Always at least use mysql_real_escape_string when adding user-provided values into the Database. You should look into binding parameters or mysqli so your query would become:
INSERT INTO `table` (`row1`) VALUES (?)
And ? would be replaced by the actual value after sanitizing the input.
In your case use:
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".mysql_real_escape_string($_POST['text'])."') ") or die(mysql_error());
Read up on SQL Injection. It's worth doing right ASAP!
Escape the string :D
http://php.net/manual/en/function.mysql-real-escape-string.php
you can use addslashes() function. It Quote string with slashes. so, it will be very useful to you when you are adding any apostrophe in your field.
$result = mysql_query("INSERT INTO `table` (`row1`) VALUES ('".addslashes($_POST['text'])."') ") or die(mysql_error());
instead of using the old mysql* functions, use PDO and write parameterized queries - http://php.net/pdo
I was also Struggling about characters when I was updating data in mysql.
But I finally came to a better answer, Here is:
$lastname = "$_POST["lastname"]"; //lastname is : O'Brian, Bran'storm
And When you are going to update your database, the system will not update it unless you use the MySQL REAL Escape String.
Here:
$lastname = mysql_real_escape_string($_POST["lastname"]); // This Works Always.
Then you query will update certainly.
Example: mysql_query("UPDATE client SET lastname = '$lastname' where clientID = '%"); //This will update your data and provide you with security.
For More Information, please check MYSQL_REAL_ESCAPE_STRING
Hope This Helps
Just use prepared statements and you wouldn't have to worry about escaping or sql injection.
$con = <"Your database connection">;
$input = "What's up?";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
If you are using php version > 5.5.0 then you have to use like this
$con = new mysqli("localhost", "your_user_name", "your_password", "your_db_name");
if ($con->query("INSERT into myCity (Name) VALUES ('".$con->real_escape_string($city)."')")) {
printf("%d Row inserted.\n", $con->affected_rows);
}

Categories