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
));
}
Related
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:
INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');
As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.
So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:
$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
"firstname"=>$firstName,
"lastName"=>$lastName));
So my question is: Is there any way to bind in a multi-insert statement? Something like:
INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.
The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
$stmt->execute($name);
}
If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
$stmt->execute($name);
}
$pdo->commit();
Just create your query text wtih ? placeholders as:
INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
And execute it. Sample code can be:
$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)']; // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
i am having a problem with inserting records to my tables as i want to insert values into specific columns if only the value is not null, my query goes like this
i have tried:
INSERT INTO users(id,name,phone,address) VALUES($userId,$userName,$userPhone,$userAddress);
but it gives me error if on client side one of the parameters is not sent not all the time the client side send all the parameters (id,name,phone,address) i want to have some kind of condition instead of the handle all combinations to the query to go over this problem
You should be using prepared queries, but your immediate problem is that you aren't quoting anything:
$query = "INSERT INTO users(id,name,phone,address) VALUES('$userId', '$userName', '$userPhone', '$userAddress')";
Now, assuming you're doing this properly using a PDO connection, this is how you should be doing it to protect your database:
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$query = "INSERT INTO users (id, name, phone, address) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$result = $stmt->execute(array($userId,$userName,$userPhone,$userAddress));
if ($result) {
//success
} else {
//failure
}
Put ' inside VALUES () like '$userId'.
INSERT INTO users(id,name,phone,address) VALUES('$userId','$userName','$userPhone','$userAddress');
If parameter are not coming, then let it Insert Null in DB Table column. (Allow Null). And, if you don't want to insert NULL in DB Table column, then assign any default value before inserting.
I have a form something like below:
<input name="first_name[]" type="text">
<input name="last_name[]" type="text">
<input name="email[]" type="email">
I am using while loop to print/echo number of groups of above form fields it required.
There will be multiple data in it, i'm not understanding how use insert query to insert data in mysql table using php.
First, you will need to know how many records you are trying to insert. I used first_name for this, but you could use any of them. (I am assuming since these are grouped together that you will always have the same number of first_name, last_name, and email.):
$count = count($_POST['first_name']);
After you know that, you can build an SQL statement that will insert all of the records in one query:
$sql = "INSERT INTO people (first_name, last_name, email) VALUES ";
$sql .= implode(', ', array_fill(0, $count, '(?, ?, ?)'));
The second line (implode...) will create sets of placeholders in the statement for each record you are trying to insert. (The three question marks represent the three columns you are inserting.) For example, if you had two field groups, the statement would look like:
INSERT INTO people (first_name, last_name, email) VALUES (?, ?, ?), (?, ?, ?)
After you have created the SQL string, you can create a new PDO connection and use that connection to create a prepared statement using your SQL.
$pdo = new PDO($dsn, $user, $password);
$statement = $pdo->prepare($sql);
Next you need to bind your values to the prepared statement. There are various different ways to do this. Here is one example:
// Create a multidimensional array using each of the fields from your field groups
$columns = array($_POST['first_name'], $_POST['last_name'], $_POST['email']);
$index = 1; // This is the index of the placeholder in the prepared statement
for ($i=0; $i < $count; $i++) { // This will loop as many times as you have field groups
$row = array_column($columns, $i);
// using array_column will pull everything from the $i index of each of the sub-arrays
// e.g. first_name[$i], last_name[$i], email[$i]
foreach ($row as $value) {
// bind the value and increment the index
$statement->bindValue($index, $value);
$index++;
}
}
After you have bound all the parameters, you can execute the prepared statement:
$statement->execute();
You can try something like this (you can find comments in the code):
if (isset($_POST['yourSubmitButton']) && isset($_POST['first_name'])) {
try {
$conn = new PDO("mysql:host=localhost;dbname=mysql", 'db_username', 'db_password');
}
catch(PDOException $e) {
echo $e->getMessage();
die();
}
$sql = 'INSERT INTO your_table (first_name, last_name, email) VALUES ';
$sql_append = array(); //Here we have the placeholder to be inserted
$binds = array(); //Here he have the values for the placeholders
for($i = 0; $i < count($_POST['first_name']); $i++) {
if (!( isset($_POST['first_name'][$i]) && isset($_POST['last_name'][$i]) && isset($_POST['email'][$i]) )) {
//We need all the values to be valid
continue;
}
//Add the placeholders and bind values
$sql_append[] = '(first_name = :first_name'.$i.', last_name = :last_name'.$i.', email = :email'.$i.')';
$binds[':first_name'.$i] = $_POST['first_name'][$i];
$binds[':last_name'.$i] = $_POST['last_name'][$i];
$binds[':email'.$i] = $_POST['email'][$i];
}
//Implode and add to the query and then execute
$sql = $sql.implode(', ', $sql_append).';';
$stmt = $conn->prepare($sql);
$stmt->execute($binds);
}
If you have 2 rows $sql will have:
echo $sql;
Result:
INSERT INTO your_table (first_name, last_name, email) VALUES (first_name = :first_name0, last_name = :last_name0, email = :email0), (first_name = :first_name1, last_name = :last_name1, email = :email1);
Hello I'd like to insert all from $_SESSION into rows $key with value $value
so something like foreach ($_SESSION as $key => $value) {}
Imlooking at:Best way to INSERT many values in mysqli?
name of rows in mysqli is same as names of given $key .I need to insert each $value in its $key (row)
Code:
$query = "INSERT INTO testtable VALUES (?)";
$stmt = $dbc->prepare($query);
$stmt->bind_param("s", $key);
$mysqli->query("START TRANSACTION");
foreach ($_SESSION as $key => $value) {
$stmt->execute();
}
$stmt->close();
$mysqli->query("COMMIT");
Your query has a syntax error, which you never bothered checking for:
$query = "INSERT INTO testtable podatki VALUES (?)";
^^^^^^^^^^^^^^^^^
If that's really the table name, then it should be quoted with backticks:
$query = "INSERT INTO `testtable podatki` VALUES (?)";
^-----------------^
if podatki is a field name, then it should be
$query = "INSERT INTO testtable (podatki) VALUES (?)";
^-------^
And also never assume that a DB operation succeeded. ALWAYS check for errors:
$stmt = $dbc->prepare($query);
if (!$stmt) {
die(mysqli_error($dbc));
}
The error is saying that you are trying to call a member function, namely bind_param(), on a non-object.
That means that this line:
$stmt = $dbc->prepare($query);
is not succeeding,
and thus you have an incorrect return value that is set as the value of $stmt
so when you try to call bind_param it fails because $stmt is not the type of object that it was expecting.
I have a fairly simple insert statement
<...>
if (!empty($attributes)) {
$sql = 'INSERT INTO `part_attrs` (`part_id`, `attr`, `type`, `list_order`) VALUES (?, ?, ?, ?)';
foreach($attributes as $key => $attribute) {
$this->db->query($sql, array($partid, $attribute[0], $attribute[1], $key));
$attrid = $this->db->insert_id();
echo $attrid.'<br />';
if (strlen($attribute[2]) > 0) {
$values = explode(',', $attribute[2]);
$sql = 'INSERT INTO `attr_values` (`attr_id`, `field_values`) VALUES (?, ?)';
foreach ($values as $value) {
$this->db->query($sql, array($attrid, trim($value)));
}
}
}
}
<...>
The odd thing is only one or two of the rows are being inserted. I put that echo line in to see the row id's it was returning for each insert since I'm not getting any errors. If for example I insert three items it will return something like 18, 124, 128. Where the 18 id is the next and expected id so this row gets inserted and then the rest don't. Any ideas what might be wrong?
You are changing the value of $sql inside your second if statement. 124 and 128 is attributes from the attr_values table. Consider using another variable name inside your if statement, or move the first assignment to $sql inside the foreach loop (move it down one line).