$db = new mysqli('localhost','x','x','rock');
$q = $db->query("INSERT INTO names (name,surname) VALUES ('jack','daniel')");
var_dump($q); // boolean true
echo $db->info;
doing everything as described in manual but still returns nothing.
If the insert statement is one of the below info function will return result
INSERT INTO...SELECT...
INSERT INTO...VALUES (...),(...),(...)
And your insert is not satisfying this condition.
you have
INSERT INTO names (name,surname) VALUES ('jack','daniel')
if you change this to insert more than one record you will see the result from info function
if you change your insert query to insert multiple record in once you will get result
Try with below
INSERT INTO names (name,surname) VALUES ('jack','daniel'),('jack2','daniel2')
Related
Sorry if the title is unclear. Basically I have a query that inserts multiple rows like this:
//Build Query
$querySQL = ('
INSERT INTO myTable (col1, col2)
VALUES (val1, val2), (val1, val2);
');
//Run query
$db->query($querySQL);
//Get the last inserted id
$last_id = $db->insert_id;
echo $last_id;
When I run this query, I will insert two rows into the "myTable" table. Let's say the id's are k and k+1. You would expect that the code would print k+1 but it doesn't! It prints k.
How come? And how safe is it to assume that the return value of insert_id will always be the first row inserted when inserting in this way?
Thanks!
I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.
I have a simple MYSQL query:
INSERT INTO table (col1,col2) VALUES ('1','2')
ON DUPLICATE KEY UPDATE col1 = '1', col2 = '2'
I use PHP PDO statements to query the database. Is there a way to know if the query executed resulted into a new inserted row or an existing was updated?
One way to do so is to get the number of rows before executing the query, then get the number of rows after executing the query, if they're not equal, it means a new row was inserted and if they are equal, it means a row was updated.
$sql = "SHOW TABLE STATUS LIKE 'TABLE_NAME'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
$number_of_rows_before = $row['Rows'];
// Do your query here, afterwards
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
$number_of_rows_after = $row['Rows'];
// If condition
if($number_of_rows_before == $number_of_rows_after) // Update was executed
else // a new row was inserted.
Just use mysqli_affected_rows,it returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
From PHP documentation:
In the case of "INSERT ... ON DUPLICATE KEY UPDATE" queries, the return value will be 1 if an insert was performed, or 2 for an update of an existing row.
see https://www.php.net/manual/en/function.mysql-affected-rows.php
From Mysql manual:
"With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if
the row is inserted as a new row and 2 if an existing row is updated."
See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
This is the most reliable way to do it.
maybe you put the answer right into the query like:
INSERT INTO table (col1,col2, col_type) VALUES ('1','2','inserted')
ON DUPLICATE KEY UPDATE col1 = '1', col2 = '2', col_type = 'updated'
How can I display the numbers of affected rows in this:
$sql = $conn->prepare ("UPDATE countries SET country=:country");
$sql->bindValue(":country", "blablaa");
$sql->execute();
And how can I show the last inserted ID with this:
$sql = $conn->prepare ("INSERT INTO countries (country) VALUES (:country)");
$sql->bindValue(":country", "test");
$sql->execute();
echo $sql->lastInsertId(); // id of last inserted
I tried, but am receiving an error call to undefined method PDO::lastInsertId()
I think this can help you:
PDOStatement::rowCount()
returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
http://php.net/manual/en/pdostatement.rowcount.php
$sql->lastInsertId();
Needs to be replaced with
$dbh->lastInsertId();
Where $dbh is your PDO object.
See here for more information.
exec returns the number of affected rows, execute only returns a true or false value.
In PHP, I am using PDO with the pgSQL drivers. I wanted to know how to get the value of the "RETURNING" clause given in the INSERT sql query.
My current code looks like this,
$query = 'INSERT INTO "TEST" (firstname, lastname) VALUES ('John', 'Doe') RETURNING user_id';
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
Obviously
$queryHandle->execute();
returns TRUE or FALSE. But I wanted to get the value of "user_id" if the insert was successful. Can you guys give me a pointer as to how to go about it? Thanks.
$ret = $queryHandle->fetchColumn();
Will return a single value instead of an array.
Did you tried to treat the command as a select returning, running
$ret=$queryHandle->fetchAll();
I am doing it like this (PHP 8.1.13, PostreSQL 15):
$query = "INSERT INTO test (firstname, lastname) VALUES ('John', 'Doe') RETURNING id";
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
$last_id = $connection->lastInsertId('test_id_seq');
I took 'test_id_seq' from the following SQL, i.e. it is [table]_[column]_seq
CREATE TABLE IF NOT EXISTS public.test
(...
id integer NOT NULL DEFAULT 'nextval('test_id_seq'::regclass)',
CONSTRAINT test_pkey PRIMARY KEY (id)
)