I can't figure out what is wrong with my logic here. The first query returns four items ( I confirmed that). I want to insert these ids in another table. Four inserts occur but all with the first id only. What is wrong here?
$query = "SELECT id FROM table1 WHERE item IN (".$x.") ORDER by id";
$result = $mysqli->query($query);
$sqq = "INSERT INTO table2 (item1, item2, item3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sqq);
while($row = $result->fetch_object()) {
$stmt->bind_param('ssi', $it1, $it2, $row);
$stmt->execute();
}
The function fetch_object() returns an object, but you're trying to use it as an integer. You should use $row->id to get the value.
while($row = $result->fetch_object()) {
$stmt->bind_param('ssi', $it1, $it2, $row->id);
$stmt->execute();
}
Related
I am a Newbie. I am trying to get all the users_id from users table in a comma separated value like 1001,1002,1003 etc then insert them as a comma separated value directly in tmpOrder table sq_id column. So far I have written below code but it is not inserting comma separated value. If I take foreach loop then it inserts an individual row for each user_id but I need to insert a single row with all the comma separated id's in sq_id column
$sql="SELECT users.id as user_id,age FROM users";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
echo $data[0];
}
$stmt1 = $con->prepare("INSERT INTO tmpOrder(id,sq_id)
VALUES ($id,implode(',',$data[0]");
$stmt1->execute();
I would use a single query, using GROUP_CONCAT to generate a comma separated list from users and INSERT that directly into tmpOrder using an INSERT ... SELECT query:
$sql = "INSERT INTO tmpOrder(id, sq_id)
SELECT ?, GROUP_CONCAT(id)
FROM users";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
Hope this helpful...
INSERT
INTO tmpOrder(id,sq_id)
VALUES (
$id,
(
SELECT
GROUP_CONCAT(users.id SEPARATOR ',')
FROM
users
)
)
So, I have problem with inserting data into 2 tables directly using subquery and last insert id.
i have following codes
if (isset($_POST['recipient']))
$recipient = sanitize($_POST['recipient']);
if (isset($_POST['message']))
$message = sanitize($_POST['message']);
$sql = "INSERT INTO message (senderID, message)
VALUES (?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, "is", $userID, $message);
mysqli_stmt_execute($stmt);
$newID = mysqli_insert_id($connection);
$sql2 = "INSERT INTO message_recipient (messageID, recipientID)
SELECT ?, userID
from user
where username = $recipient";
if ($stmt2 = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt2, "ii", $newID, $recipient);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
}
for the $stmt2 ,it works well in phpmyadmin, but without the prepared statement. The first query works well, it can add data, but can't the second. Also, i dont know why the first query will insert 2 data, with first data correct and second false.
Is the way i get last insert id wrong, or my second query is false?
Any help given really appreciated. thank you so much
I have this simple pre-sort database input thing, I've created this before, what I'm screwing up is the while aspect.
There are two different tables: a table that keeps track of keyword frequencies and a table for the entries themselves paired with the keyword.
What I'm doing is saving something by a keyword, I check if the keyword exists, if it does, I increment the count of that keyword and then proceed to add the entry to the entry database, if not I create a new entry of that keyword in the keyword table and set the count as 1, then add the entry to the entry database.
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s',$key);
$stmt->execute();
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
// count comes out here
// echo $count;
if($count==0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
}
}
<?php
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s', $key);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_row()){
$count = $row[0];
}
$stmt->close();
// count comes out here
// echo $count;
if($count == 0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss', $id, $poster, $key, $entry, $date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
$stmt->close();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
$stmt->close();
}
}
?>
This should do the trick for you, you can't use fetch_row() directly on $stmt, that was your mistake.
There are two issues
first
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
should be replaced by simply
$count = $stmt-rowCount()
You actually don't need the 'keys' table. Consider your DB schema again. The keys table is superfluous. The 'entry' table will suffice just update the entry table and you are good. All information can be obtained by querying the entry table rightly
I have this following example query, which works - I CAN insert values into my MySQL table, which also includes an unique id column. I want to get the id from the inserted row, after I execute the query. However what I get is 0 every time ($gotId=0).
What am I doing wrong?
$stmt = $conn->prepare("INSERT INTO ....... ");
$stmt-> bind_param("ss", ....);
$stmt->execute();
$gotId = $conn->insert_id;
Full query:
$conn = $db->connect();
$stmt = $conn->prepare("INSERT INTO table(value1, value2) VALUES(?, ?)");
$stmt-> bind_param("ss", $value1, $value2);
$stmt->execute();
$gotId = $conn->insert_id;
After calling the execute() method on the PreparedStatement, the id of the insert row will be in the insert_id attribute Only read it.
$stmt->execute();
$gotId = $stmt->insert_id;
Taken from here
$query = "INSERT INTO .......";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
More Info
I am entering objects from an array into a database.
I have an array called $graphObject
I am looping through the array like this,
foreach($graphObject['tagged_places']->data as $data) {
}
Then I want to take each one of these values and enter them in to the mysql DB with PDO
$data->id
$data->created_time
$data->place->id
$data->place->location->latitude
$data->place->location->longitude
$data->place->name
I am confused on how to write this loop to enter each one of these fields foreach time a new field exist.
Assuming the DB connection is open and the fields in the DB are named
id created_time place_id latitude longitude name
How would I write this with PDO?
What you probably want to do is to build your insert in a loop and then simply execute a single insert statement. So something like this:
$sql = <<<EOT
INSERT INTO table (
`id`,
`created_time`,
`place_id`,
`latitude`,
`longitude`,
`name`)
VALUES
EOT;
foreach($graphObject['tagged_places']->data as $data) {
// add values into string you can remove single quotes if not needed
// (i.e. for numeric data types)
$values = <<<EOT
(
'{$data->id}',
'{$data->created_time}',
'{$data->place->id}',
'{$data->place->location->latitude}',
'{$data->place->location->longitude}',
'{$data->place->name}'
),
EOT;
$sql .= $values;
}
$sql = rtrim(',', $sql);
// execute query using $sql
// assume you have properly instantiated PDO object in $pdo
$result = $pdo->query($sql);
if (false === $result) {
// something went wrong, so log an error
// this assumes you have not configured PDO to throw exceptions
error_log(var_export($pdo->errorInfo(), true));
} else {
// continue doing whatever you want to do
}
Create a prepared statement:
$stmt = $db->prepare('
INSERT INTO table
(id, created_time, place_id, latitude, longitude, name)
VALUES
(?, ?, ?, ?, ?, ?)
');
Execute it on each loop
foreach($graphObject['tagged_places']->data as $data) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->name
));
}