I am unable to understand on how to apply insert query with select statement:
I have gone through this question also:
MySQL INSERT from a SELECT with PDO
But where is the VALUES part??
Like I have this query to insert in Mysql and here I use Values also:
$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable (name, user_id) VALUES(:sname, :uid)');
foreach($UploadData AS $DataValue)
{
$query->execute(array(':sname' => $DataValue['Name'],':uid' =>$_SESSION['uid']));
}
$db_conn->commit();
My motto is to check if the name exists with the same uid it shouldn't import the data otherwise it should. But Where are the values part :/ I am blind :P
EDIT1: From MySQL INSERT from a SELECT with PDO
How will this code block work if no VALUES is supplied?
$sql_enc = '
INSERT INTO sessionid (enc_id, enc_pass, enc_date)
(SELECT AES_ENCRYPT(username, :aeskey), AES_ENCRYPT(pwd, :aeskey), DATE_ADD(NOW(), INTERVAL 15 SECOND) FROM users WHERE username = :username)
';
$res_enc = $pdo->prepare($sql_enc);
$res_enc->bindParam(':aeskey', $aeskey);
$res_enc->bindParam(':username', $username);
$res_enc->bindParam(':pwd', $username);
$res_enc->execute();
$res_enc = null;
There are two valid INSERT syntax:
INSERT
INTO `table` [(field1, field2)]
VALUES ( 'val1', 'val2' )
Or
INSERT
INTO `table` [(field1, field2)]
SELECT 'val1', 'val2'
the selected columns are your value fields.
#comments:
Replace:
http://dev.mysql.com/doc/refman/5.5/en/replace.html
Procedures:
http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html
You are defining the parameters :sname and :uid in your loop. The method execute takes the params and "put them" inside your query before executing this one.
On other words, the query is compiled when you call prepare() and the parameters are applied when you call execute().
Edit:
Ok I didn't understand.
The query includes a "SELECT" part which gives the values to insert. With SELECT you must not write "VALUES", as the documentation says:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Related
I'm having the following query, it contains a Temporary Table. If I use a Temporary Table, it returns an EMPTY ARRAY. If I removed the Temporary Table it returns an appropriate records.
The following SQL Query contains a simple query, I just created a Temporary Table and inserted some records and I'm doing SELECT Query in that Temporary Table. I executed the same code in phpMyAdmin, it returns an appropriate records, but in PDO returns an EMPTY ARRAY.
Sample and Simple SQL Query:
Case #1: With Temporary Table - Returns an EMPTY ARRAY
<?php
$query = <<<SQL
CREATE TEMPORARY TABLE TempContact (
ContactId int,
FirstName varchar(30),
LastName varchar(30),
IsActiveContact Boolean
);
INSERT INTO TempContact (ContactId, FirstName, LastName, IsActiveContact)
SELECT CT.ContactId, CT.FirstName, CT.LastName,
CASE WHEN SL.SalesId IS NOT NULL THEN TRUE ELSE FALSE END AS IsActiveContact
FROM Contact CT
LEFT JOIN Sales SL ON CT.ContactId = SL.ContactId;
SELECT TC.* FROM TempContact TC;
SQL;
$stmt = $db->prepare($query);
$result = $stmt->execute() ? $stmt->fetchAll() : null;
?>
Case #2: Without Temporary Table - Returns an appropriate records
<?php
$query = <<<SQL
SELECT CT.ContactId, CT.FirstName, CT.LastName,
CASE WHEN SL.SalesId IS NOT NULL THEN TRUE ELSE FALSE END AS IsActiveContact
FROM Contact CT
LEFT JOIN Sales SL ON CT.ContactId = SL.ContactId;
SQL;
$stmt = $db->prepare($query);
$result = $stmt->execute() ? $stmt->fetchAll() : null;
?>
My actual code is so complex, due to easy understanding I added this simple query.
I also checked for any error in my Query (Case #1 Query) using print_r($stmt->errorInfo());, but it returns an EMPTY ARRAY (i.e., No Error in my Query);. Moreover its not throwing any PDOException.
Kindly assist me, how to get the records from the Temporary Table SELECT
With PDO you're supposed to execute one query at a time. It's not like the SQL console where you can push in a bunch of statements at once.
You're expected to check that each query completed successfully before moving on to the next one. If you split this up into several prepare/execute pairs it will work as-is. The reason the second succeeds is because it consists of a single statement.
PHP PDO fetchAll() returns empty array while SELECTing Temporary Table
Obviously, it is not true. Anyone can run the following code utilizing a temporary table and see the result
$pdo->query("CREATE temporary TABLE tmptest (id int auto_increment primary key, name varchar(255))");
$stmt = $pdo->prepare("INSERT INTO tmptest VALUES (NULL, ?)");
foreach (['Sam','Bob','Joe'] as $name)
{
$stmt->execute([$name]);
}
$stmt = $pdo->prepare("SELECT * FROM tmptest");
$stmt->execute();
var_export($stmt->fetchAll(PDO::FETCH_KEY_PAIR));
which outputs the expected
array (
1 => 'Sam',
2 => 'Bob',
3 => 'Joe',
)
While your problem is coming from the fact that you are running multiple queries in a single call and so the first fetchAll() is naturally returns an empty result as the first query returns nothing. To get your data you should be either run your queries in separate statements or move the internal pointer to the next result and then call for fetchAll():
$pdo->query("CREATE temporary TABLE tmptest (id int auto_increment primary key, name varchar(255))");
$pdo->query("CREATE temporary TABLE tmptest2 (id int auto_increment primary key, name varchar(255))");
$stmt = $pdo->prepare("INSERT INTO tmptest VALUES (NULL, ?)");
foreach (['Sam','Bob','Joe'] as $name)
{
$stmt->execute([$name]);
}
$stmt = $pdo->prepare("INSERT INTO tmptest2 SELECT * from tmptest;SELECT * FROM tmptest2");
$stmt->execute();
$stmt->nextRowset();
var_export($stmt->fetchAll(PDO::FETCH_KEY_PAIR));
I have been working on my first webapp and I hit a bit of a wall. I have a table in my db set up as follows:
student_id(student_id, first_name, last_name, bdate, etc...)
I also have several tables for classes set up similarly to this
class_table(id, student_id, quiz_1, quiz_2, etc....)
student_id is how I would like to track everything, from my understanding, this would be a primary key that would become a foreign key on the class tables.
What I would like to do is create an entry for the student on each class table when the php script I am writing creates a new student. This is what my query looks like:
$query = "INSERT INTO student_id(0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table(0, LAST_INSERT_ID(), '$quiz_1', $quiz_2'...etc)";
Is this the right way to do this? I keep getting an error from my mysqli_query... so I am guessing this is where the problem is. How would I achieve this?
mysqli_query() (and mysql_query()) will only execute a single query. You would need to perform two calls to mysqli_query() or use mysqli_multi_query(), which will execute multiple queries in one call.
You're missing the VALUES clause:
$query = "INSERT INTO student_id VALUES (0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), '$quiz_1', '$quiz_2'...etc)";
and you will need to use the mysqli_multi_query() function. See the example at http://www.php.net/manual/en/mysqli.multi-query.php#106126:
if ($mysqli->multi_query($query)) {
$i = 0;
do {
$i++;
} while ($mysqli->next_result());
}
if ($mysqli->errno) {
echo "Batch execution prematurely ended on statement $i.\n";
var_dump($statements[$i], $mysqli->error);
}
You could also create a stored procedure, and call it with all the needed parameters:
CALL insert_student('$first_name', '$last_name', '$quiz_1', $quiz_2', ... etc);
Here's an example:
CREATE PROCEDURE add_student(
IN v_first_name VARCHAR(50),
IN v_last_name VARCHAR(50),
IN v_quiz_1 VARCHAR(255),
IN v_quiz_2 VARCHAR(255)
)
DETERMINISTIC
MODIFIES SQL DATA
proc: BEGIN
START TRANSACTION;
INSERT INTO student_id VALUES (0, v_first_name, v_last_name);
IF ROW_COUNT() <= 0 THEN
ROLLBACK;
SELECT 0 AS result;
LEAVE proc;
END IF;
INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), v_quiz_1, v_quiz_2);
COMMIT;
SELECT 1 AS result;
END;
I'm performing a transaction (using PDO), however I need to grab the insert id of the first element in the transaction, for example:
BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;
Then do the pdo stuff:
[...]
$pdo->execute();
$foo = $pdo->lastInsertId(); // This needs to be the id from the FIRST insert
Is there a way to get the last insert id from the first element in a transaction? Perhaps using something like the following:
BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
SELECT id AS user_id FROM user WHERE id=LAST_INSERT_ID()
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;
$pdo->execute();
$fooArray = $pdo->fetchAll();
$lastId = $fooArray[0]['user_id'];
Am I completely out to lunch with ^ ? Is there a better way to do this?
EDIT 1
Based on suggestion, i've updated the query to use variables... however, i don't know how to retrieve the variable values using PDO. Using $stmt->fetchAll() just returns an empty array;
BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;
You can do it this way, put the value into variable then just select it
BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;
I wrote a logger function and it inserts "insert and update queries" to database. altough I apply "mysql_real_escape_string" to the sql stament, I cannot insert it to the database.
any suggestion please?
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1 UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1)
In SQL, strings must be quoted. You are also missing a comma. Try this:
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1, 'UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1')
i have also problems with this function, then i use the addslashes() function, its not an answer but a solution.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
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)
)