Related
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;
}
I am using a simple php script to insert data into database but it's failing. The query just doesn't become successful without showing a single error which is why I am unable to figure out the problem. Some expert here help me please.
echo $name." ".$email." ".$pass." ".$phone." ".$area." ".$specialization." ".$city." ".$latitude." ".$longitude;
The result of echo is normal - without any null elements.
$query = mysqli_query($conn, "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
if ($query) {
echo "Status: Registeration Successful!";
// creating directory for user and storing dummy profile picture
//mkdir('../profiles/'.$email_trim, 0777);
//$result_copy = copy("img/dp.jpg.jpg", "../profiles/".$email_trim."/dp.jpg.jpg");
} else {
echo "Status: Err";
}
This "Status: Err" is always printed. I don't know why.
P.S I have double checked the database the field labels are fine.
UPDATE 1:
I added the
die(mysqli_error($conn));
statement and it says "DUPLICATE ENTRY '0' FOR KEY PRIMARY'.
PROBLEM AND SOLUTION:
The issue was that I had an 'id' field which was primary key of the table but it was not set to AUTO_INCREMENT. So, whenever I tried to insert a new record, I was actually inserting entries with duplicate PKs which was the issue. I change it to AUTO_INCREMENT and it solved the problem.
It seems you try to insert a new element with a PK = 0, but there is already a record with this key !
What is the primary key of your table ? Do you use an "id" field which is not shown in your insert statement ? Is this field AUTO_INCREMENT ?
It would be helpful to see the structure of your 'users' table.
Wild guess: looks like you may have defined an "id" column (or with whatever other name) which is primary key with default value "0", but it's not auto increment. That way you can insert 1 row and it will get "0" as "id" column's value, but you cannot insert another row because it will also try to use default value "0", which cannot happen as primary key has to be unique.
If that is the case, then please alter users table and make sure that the primary key column is also 'auto increment'.
Please check the proper error by adding below mentioned code inside else:
echo mysqli_errno($conn) . '----' . mysqli_error($conn);
<?php
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ") or die(mysqli_error());
$query = mysqli_query($conn, "INSERT INTO `users` (`name`, `email`, `pass`, `phone`, `area`, `specialization`, `hospital`, `city`, `latitude`, `longitude`)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude') ");
use ` Tick maybe because there's some reserved word in your fields.
I think you doubled your close parenthesis and do not put $conn inside the query..
$query = "INSERT INTO users (name, email, pass, phone, area, specialization, hospital, city, latitude, longitude)
VALUES ('$name', '$email', '$pass', '$phone', '$area', '$specialization', '$hospital', '$city', '$latitude', '$longitude')";
mysqli_query($query, $conn);
Something like this. I hope this helps
I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";
I need your help to fix my problem..
first I have 2 tables in mysql dbase.. here are the structures :
doctor1:
--------
no_que autoincrement pk,
doctor_name,
id_patient,
date,
time
status_que:
----------
id_patient,
doctor_name,
no_que fk,
date,
time
I want to insert data into doctor1 and the data will be the same at status_que..
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = #mysql_query($query) or die("REPORT Failed to save data.");
$last_insert_no_que = mysql_insert_id();
#query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = #mysql_query($query2) or die("REPORT Failed to save data.");
but that code doesn't work
it works ! I only have to delete "#" operator.. :) ~ thx you
so here is my code :
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = mysql_query($query) or die(mysql_error());
$last_insert_no_que = mysql_insert_id();
$query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = mysql_query($query2) or die(mysql_error());
>
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')";