This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 5 years ago.
I have a very specific problem and nothing I could find online was able to tell me where my error was.
I want to pass two mysql queries at once. Separately, they work perfectly but together they fail. I've tries JOIN, adding ; and the multi_queries method. Everything fails.
Now I am stuck with this code:
// data insertion
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date')";
$sql.= "DELETE FROM comments_validation WHERE id = $id";
if ($conn->multi_query($sql) === TRUE) {
header('Location: http://url.com/index.php?success');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
And the error:
Error: INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('some values')DELETE FROM comments_validation WHERE id = 'some other value'
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 'DELETE FROM comments_validation WHERE id = 'some other value' at line 1
Thanks in advance!
You have to add a ; at the end of this sql statement
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date');";
^here
Please add semi-colon as string at the end of every query in multi query.
// data insertion
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date');";
$sql.= "DELETE FROM comments_validation WHERE id = $id";
if ($conn->multi_query($sql) === TRUE) {
header('Location: http://url.com/index.php?success');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Related
This question already has answers here:
Multiple mysql INSERT statements in one query php [duplicate]
(8 answers)
Closed 3 years ago.
I'm trying to insert multiple data in one table, however I got an error that 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 'INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf')INSERT INT' at line 1
Here's the method:
$sql = "INSERT INTO author (firstname, lastname) VALUES ('Roal', 'Dahl')";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf')";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Jane', 'Doe')";
Do I need to create a for loop for this? How could this work?
You can do this :
$sql = INSERT INTO author ( firstname, lastname) VALUES ('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe');
Generally, mysqli and PDO cannot execute multiple statements in a single query. There are alternatives like mysqli_multi_query, but that is not really what you need.
Your query can have multiple rows added by appending extra sections after VALUES like so:
$sql = "INSERT INTO author (firstname, lastname) VALUES ";
$sql .= "('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe')";
You can use two options:
mysqli_multi_query
$sql = "INSERT INTO author (firstname, lastname) VALUES ('Roal', 'Dahl');";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Rasmus', 'Lerdorf');";
$sql .= "INSERT INTO author (firstname, lastname) VALUES ('Jane', 'Doe');";
if(!$mysqli->multi_query($sql)){
echo 'Error query:'. $mysqli->error . '.';
}else{
//do any operation
}
Or use one query like:
$sql = INSERT INTO author ( firstname, lastname) VALUES ('Roal', 'Dahl'), ('Rasmus', 'Lerdorf'), ('Jane', 'Doe');
if(!$mysqli->query($sql)){
echo 'Error query:'. $mysqli->error . '.';
}else{
//do any operation
}
Change $mysqli with your connection
$query = "Insert into $sql_table (date, Firstname, Lastname, StudentID, Score) values ('$date', '$Firstname', '$Lastname' , '$StudentID' , '$mark')";
// execute the query
$result = mysqli_query($conn, $query);
if(!$result)
{
echo "<p>Error with " , $query , "</p>";
}
else
{
echo "<p>Table updated Successfully</p>";
}
Error with Insert into attempts (date, Firstname, Lastname, StudentID, Score) values ('2018-10-21 10:30:21pm', 'jhjsdhfhje', 'bnsdb' , '1023456789' , '6')
Probably going to be that first parameter, but would depend on your table structure.
If date is a date column then MySQL will be expecting a "Y-m-d" formatted string, if it's a datetime then it will be expecting a "Y-m-d H:i:s".
My suggestion would be to drop the "pm" and see if that works.
Looks like I'm connecting to the server just fine. The problem seems to happen when it runs the query. It keeps saying
Error Querying Database
Here is my code:
<?php
$dbc = mysqli_connect('localhost', 'elvis_store')
or die('Error connecting to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'Customer added.';
mysqli_close($dbc);
?>
You are getting this error because in your MySQLi connection you only give a location and username. You do not give a database name to be used. if you have no password, you need to write your connection like this:
$dbc = mysqli_connect('localhost', 'elvis_store', NULL, 'dbName)
or
$dbc = mysqli_connect('localhost', 'dbUsername', NULL, 'elvis_store')
if "elvis_store" is the database name and not the username. Remember, a mysqli connection is: mysqli_connect(dbLocation, dbUsername, dbPassword, dbName).
Also, as Ed has pointed out in another answer, there is also a syntax error in your MySQL statement. Here is the snippet from Ed's answer:
$query = "INSERT INTO email_list (first_name, last_name, email) " . "VALUES ('$first_name', '$last_name', '$email')";
You have multiple problems.
Problem 1: Syntax error
Your query has a typo (a missing space). Your query code
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
produces this query:
INSERT INTO email_list (first_name, last_name, email)VALUES ('$first_name', '$last_name', '$email')
-- ^ syntax error, missing space
To fix it, change your code to this:
$query = "INSERT INTO email_list (first_name, last_name, email) " .
"VALUES ('$first_name', '$last_name', '$email')";
At least for testing purposes, you probably should look at the output of mysqli_error() instead of using a generic message like Error querying database. Even in production, you'll want to trap and log the real error somehow.
Problem 2: You don't select a database
Edit: I missed this in my first glance at your question, but as Stephen Cioffi points out, you also need to select a database before running your query. You can do this with the schema parameter to mysqli_connect() or by using mysqli_db_select().
Both of these issues—the typo and the failure to select a database—will cause problems; you must fix both.
Problem 3: Huge SQL Injection Vulnerability
This is not strictly part of the answer, but it's important. You are wide open to SQL injection. You need to use prepared statements. Otherwise, you are going to get hacked. Imagine that the POSTed firstname is this:
', (SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1), 'eviluser#example.com') --
Your query becomes (with some added formatting):
INSERT INTO email_list (first_name, last_name, email)
VALUES ('',
(SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1),
'eviluser#example.com'
) -- ', 'value of lastname', 'value of email')
Then, when you email your users, somebody's going to get an email with a recipient like
"Duke,mySup3rP#ssw0rd!" <eviluser#example.com>
And... you're hosed.
(Hopefully, you're salting and hashing passwords, but still, this is disastrous.) You must use prepared statements.
I'm new to MySQL. Whats wrong with this code? It doesn't update data.
"INSERT INTO highscores (name, score, maila, ip)" . "VALUES ('$name', '$score', '$maila', '$ip')" .
"ON DUPLICATE KEY UPDATE score;" . "UPDATE highscores SET (if score>'$score') {score=$score} WHERE name=$name"
This works:
"INSERT INTO highscores (name, score, maila, ip) ".
"VALUES ('$name', '$score', '$maila', '$ip') " . "
on duplicate key update score = greatest(score, $score)"
Thanks to binaryLV:
MSQL: How to overwrite entry only if new one is higher? else create new entry
When you use ON DUPLICATE KEY UPDATE, you must also specify what to update, that is, in PHP, the right query would be:
$q = "INSERT INTO highscores (name, score, maila, ip) ".
"VALUES ('$name', '$score', '$maila', '$ip') ".
"ON DUPLICATE KEY UPDATE score='$score'";
This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";