I have my 3 arrays which I put into these variables:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
I want to insert this array of values into the sql table like
ID | Anzahl | title | groesse
-----------------------------------------
1 | 4 | Schulkind Shirt gelb | S
1 | 5 | Friends Shirt lila | M
1 | 3 | Shirt Sesamstraße | S
1 | 4 | Shirt Sesamstraße | L
But I have no clue how to insert it like shown above
I split them up with for each so far, that's where I'm stuck
foreach ($anzahl as $einzelanzahl) {
echo $einzelanzahl['test_bestellte_anzahl'];
}
foreach ($title as $einzeltitle) {
echo $einzelname['test_bestellte_groesse'];
}
foreach ($groesse as $einzelgroesse) {
echo $einzelgroesse['test_bestellte_artikel'];
}
Thanks in advance!
If all arrays with the same length:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$stmt = $mysqli->prepare("INSERT INTO MyTable (`Anzahl`, `title`,
`groesse`) VALUES (?, ?, ?)");
for ($i = 0; $i < count($title); $i) {
// prepare and bind
$stmt->bind_param($title[$i], $anzahl[$i], $groesse[$i]);
$stmt->execute();
}
$stmt->close();
$mysqli->close();
Assuming the three arrays are always keyed identically, use a single loop:
$arrayOne = array('a', 'b', 'c', 'd');
$arrayTwo = array('w', 'x', 'y', 'z');
$arrayThree = array('m', 'n', 'o', 'p');
foreach ($arrayOne as $key => $valueOne) {
$valueTwo = $arrayTwo[$key];
$valueThree = $arrayThree[$key];
// save your table row to database...
echo "key: $key one: $valueOne two: $valueTwo three: $valueThree<br/>";
}
/* output:
key: 0 one: a two: w three: m
key: 1 one: b two: x three: n
key: 2 one: c two: y three: o
key: 3 one: d two: z three: p
*/
I mean you can use next peace of code:
<?php
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$query = "INSERT INTO the_table (ID, Anzahl, title, groesse) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($query);
foreach ($title as $id=>$einzelanzahl) {
$stmt->execute([1, $title[$i], $anzahl[$i], $groesse[$i]]);
}
PHP PDO online
Related
I am trying to update multiple rows in a database. I have the total number of rows in my table counted and bound to a variable:
$result = '32'
I then attempt to query each row:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'];
$substrate_desc = $_POST['substrate_desc'];
$substrate_base = $_POST['substrate_base'];
$substrate_tax = $_POST['substrate_tax'];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
My problem is when I run this script, each row in the table is filled with the last row edited. For example:
AAA | Aaaaa | 1.00 | 6.35
BBB | Bbbbb | 2.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
Becomes:
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
CCC | Ccccc | 3.00 | 6.35
How can I fix this script so it will update each row individually?
Try this:
for ($x = 0; $x <= $result; $x++)
{
if ($update = $db -> prepare("UPDATE substrates SET substrate_name = ?, substrate_desc = ?, substrate_base = ?, substrate_tax = ? WHERE substrate_id = ?"))
{
$substrate_name = $_POST['substrate_name'][$x];
$substrate_desc = $_POST['substrate_desc'][$x];
$substrate_base = $_POST['substrate_base'][$x];
$substrate_tax = $_POST['substrate_tax'][$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
if ($update -> execute() == true) {
// Success stuff...
}
else {
// Error stuff...
}
$update -> close();
}
}
I changed the "name" fields in my form to include the substrate's ID:
<input name="substrate_name_'.$substrate_id.'" />
Then did the same for the update query (where the id is defined by the loop, $x):
$substrate_name = $_POST['substrate_name_'.$x];
$substrate_desc = $_POST['substrate_desc_'.$x];
$substrate_base = $_POST['substrate_base_'.$x];
$substrate_tax = $_POST['substrate_tax_'.$x];
$substrate_id = $x;
$update -> bind_param('sssss', $substrate_name, $substrate_desc, $substrate_base, $substrate_tax, $substrate_id);
And this gave me the desired result. Thanks to Rimon Khan for the idea and to everyone who commented.
I have four Array consisting of some values. I want to insert Array with same index in same row.
Eg:
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
I want table to be some thing like this
+----+----------+-------------+------+--------+
| id | product | sub_product | plan | months |
+----+----------+-------------+------+--------+
| 1 | Facebook | Likes | 10k | 3 |
+----+----------+-------------+------+--------+
| 2 | Twitter | Boost | 20k | 6 |
+----+----------+-------------+------+--------+
What will be the best way to achieve this such that Index of each array falls in same row? I want to insert in HTML table
If you want to execute mysql_query in single shot then
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
$query = 'insert into TABLE (product,sub_product,plan,months) values';
foreach( $product as $index => $col ){
$query .= "( '".$product[$index]."', '".$sub_product[$index]."', '".$plan[$index]."', ".$months[$index]." ),";
}
$query = rtrim( $query, ',');
mysqli_query(mysql_query);
This will be faster than executing multiple mysql_query function in a loop.
Try This Code,
foreach($product as $key=>$p){
$data = array(
'product'=>$p,
'sub_product'=>$sub_product[$key],
'plan'=>$plan[$key],
'months'=>$months[$key]
);
//Code to insert this array to Database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO `table`('product','sub_product',...) VALUES ($data['product'],$data['sub_product'],...)";
mysqli_close($conn);
//OR If you are using Codeigniter,
$this->db->insert('table',$data);
}
this code should work,
$product = array("Facebook", "Twitter");
$sub_product = array("Likes", "Boost");
$plan = array("10k", "20k");
$months = array(3,6);
for($i=0;$i<count($product);$i++){
$product_name=$product[$i];
$sub_product_name=$sub_product[$i];
$plan_name=$plan[$i];
$month_no=$months[$i];
echo "insert into table_name (product_name, sub_product_name, plan_name, month_no) values ('$product_name', '$sub_product_name', '$plan_name', '$month_no')";
echo "<br>";
}
Thanks
Amit
Assuming all arrays have the same length and $mysqli is a connection to your database,
for ($i=0; $i < count($product); $i++) {
$query = "INSERT INTO your_table (id, product, sub_product, plan, months)";
$query .= " VALUES ('$i', '{$product[$i]}', '{$sub_product[$i]}', '{$plan[$i]}', '{$months[$i]}')";
$mysqli->query($query);
}
Assuming that the size of all the above arrays are same at a given point of time and their indexing is consistent you can use the following code:
<?php
$product = array('Facebook', 'Twitter');
$sub_product = array('Likes', 'Boost');
$plan = array('10k', '20k');
$months = array(3,6);
/* Connected to a mysql Database */
$i = 0; //initialize a counter
while($i < sizeof($product)) //Run the loop (Twice in this case)
{
//Store the current iteration value in variables
$current_product = $product[$i];
$current_sub_product = $sub_product[$i];
$current_plan = $plan[$i];
$current_months = $months[$i];
//Prepare the SQL statement
$sql = <<<EOD
INSERT INTO table_product(product,subproduct,plan,months)
VALUES ('$current_product','$current_sub_product','$current_plan',$current_months)
EOD;
$i++;
echo $sql . "<br />";
}
?>
Do on this way simple:
$count = count($product);
$index=0;
while($index<$count){
//do your stuff here i.e. insert query
$sql = "INSERT INTO your_table SET product='".$product[$index]."', sub_product='".$sub_product[$index]."', plan='".$plan[$index]."', months='".$months[$index]."' ";
mysql_query($sql);
$index++;
}
I do have an array something like this:
[cuisines] => Array
(
[0] => 17
[1] => 20
[2] => 23
[3] => 26
)
Now I need to update mysql table with these values. All values belong to one user.
So I tried it like this:
if (isset($_POST['cuisines'])) {
$cuisines = $_POST['cuisines'];
} else {
$error_alert[] = "Please select at least one cuisine";
}
if (empty($error_alert)) { // If everything's OK...
// Make the update query:
$sql = 'UPDATE restaurant_cuisines
SET restaurant_id = ?
, cuisine_id = ?
WHERE restaurant_id = ?';
$stmt = $mysqli->prepare($sql);
// Bind the variables:
$stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);
foreach ($cuisines as $value) {
$cuisine_id = $value;
// Execute the query:
$stmt->execute();
}
// Print a message based upon the result:
if ($stmt->affected_rows >= 1) {
echo 'updated';
}
// Close the statement:
$stmt->close();
unset($stmt);
}
But this query not updating mysql correctly. This is what I get running this script.
mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
| 4 | 26 |
| 4 | 26 |
| 4 | 26 |
+---------------+------------+
3 rows in set (0.00 sec)
What would be the problem of this script?
Hope somebody may help me out.
Thank you.
You need to bind your parameters in the loop:
// Delete old entries:
$sqlDelete = 'DELETE FROM restaurant_cuisines WHERE restaurant_id = ?';
$stmtDelete = $mysqli->prepare($sqlDelete);
$stmtDelete->bind_param($restaurant_id);
$stmtDelete->execute();
$stmtDelete->close();
unset($stmtDelete);
// now prepare to insert new values
$sqlInsert = 'INSERT INTO restaurant_cuisines (restaurant_id,cuisine_id)
VALUES (?,?)';
$stmtInsert = $mysqli->prepare($sqlInsert);
foreach ($cuisines as $value) {
// Bind the variables:
$stmtInsert->bind_param($restaurant_id, $value);
// Execute the query:
$stmtInsert->execute();
// Print a message based upon the result:
if ($stmtInsert->affected_rows >= 1) {
echo 'updated';
}
}
// Close the statement:
$stmtInsert->close();
unset($stmtInsert);
I have 2 foreach loop which gets colors and sizes. I also have for loop which generate the material number. I'm trying to achieve distribute the variables well for example I have 2 colors with 3 sizes.
This is the desired output
Material# | Color | Size
1001 | Blue | Small
2001 | Blue | Medium
3001 | Blue | Large
4001 | Green | Small
5001 | Green | Medium
6001 | Green | Large
Here's my code:
//insert material number
for($x = 1; $x <= $matnumbersize; $x++ )
{
$matnummm= str_pad($x, 3, '0', STR_PAD_LEFT);
$materialnumber = $newgennumber.$matnummm;
$matnumberr[] = $materialnumber; //materialnumber
$stmt = $db->prepare("INSERT INTO materialnumber(productID,stylecodeID,genericnumberID,materialnumber) VALUES(:pid,:scode,:gcode,:matnum)");
$stmt->execute(array(':pid' => $productID, ':scode' => $styleID, ':gcode' => $gennumID, ':matnum' => $materialnumber));
}
print_r($matnumberr);
$statement = $db->prepare("SELECT * FROM productcolor a, color b where a.productID = :pid and a.colorID = b.colorID ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$colorcode = $row['colorCode'];
$statement = $db->prepare("SELECT * FROM productsizes where productID = :pid ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$sizeCde = $row['sizeName'];
echo $colorcode.$sizeCde.'<br/>';
}
}
I tried my best but I cant think a fix of it. Thank you!
I fixed it and manage to make it shorter so here's my code
$y = 1;
$statement = $db->prepare("SELECT * FROM productcolor a, color b where a.productID = :pid and a.colorID = b.colorID ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$colorcode = $row['colorCode'];
$statement = $db->prepare("SELECT * FROM productsizes where productID = :pid ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$sizeCde = $row['sizeName'];
echo $colorcode.$sizeCde.'<br/>';
$yy= str_pad($y, 3, '0', STR_PAD_LEFT);
$newmaterialnum = $newgennumber.$yy;
$stmt = $db->prepare("INSERT INTO materialnumber(productID,stylecodeID,genericnumberID,materialnumber,color,size)
VALUES(:pid,:scode,:gcode,:matnum,:color,:size)");
$stmt->execute(array(':pid' => $productID, ':scode' => $styleID, ':gcode' => $gennumID, ':matnum' => $newmaterialnum,
':color' => $colorcode, ':size' => $sizeCde));
$y++;
}
}
I am building a system, mostly for consolidating learning but will be used in practice.
I will try and verbally explain the part of the E-R diagram I am focusing on:
Each cadet can have many uniformID's
Each Uniform ID is a new entry in table uniform, so cadets (table) may look like:
id | name | ... | uniformID
1 | Example | ... | 1,2,3
uniform table:
id | notes | cadet
1 | Need new blahh | 1
2 | Some stuff needed | 1
3 | Whatever you like | 1
On second thought, looks like I wont need that third column in the db.
I am trying to iterate through each id in uniformID, code:
<?php
$cadet = $_GET['id']; // set from URL
$query = mysql_query("SELECT `uniformID` FROM `cadets`
WHERE id = '$cadet' LIMIT 1")
or die(mysql_error()); // get uniform needed as string
// store it
while ($row = mysql_fetch_array($query)) {
$uniformArray = $row['uniformID'];
}
echo $uniformArray . " ";
$exploded = explode(",", $uniformArray); // convert into an array
// for each key in the array perform a new query
foreach ($exploded as $key => $value) {
$query(count($exploded));
$query[$key] = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
}
?>
As I say, this is mainly for consolidation purposes but I have come up with a error, sql is saying:
Fatal error: Function name must be a string in C:\wamp\www\intranet\uniform.php on line 82
line 82 is:
$query[$key] = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
I wasn't sure it would work so I tried it and now i'm stuck!
EDIT:
Thanks to everyone who has contributed to this! This is now the working code:
foreach ($exploded as $key => $value) {
//$query(count($exploded));
$query = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
while ($row = mysql_fetch_array($query)) {
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['note'] . "</td>
</tr>";
}
}
Added the while and did the iteration by nesting it in the foreach
In addition to your tables
cadets(id, ...)
uniforms(id, ...)
use a cross-product table that describes the relation between entities of cadets and entities of uniforms
cadets_x_uniforms(cadet_id, uniform_id)
For each relationship (in this case cadet x has uniform y) put a record with the respective ids into the cross-product table.
... hm, a working example will do better in this case I suppose...
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);
// fetch the uniforms of a specific cadet
$stmt = $pdo->prepare('
SELECT
c.name,u.id,u.labelid
FROM
so_cadets as c
LEFT JOIN
so_cadet_uniform as cxu
ON
c.id=cxu.cadet_id
LEFT JOIN
so_uniforms as u
ON
cxu.uniform_id=u.id
WHERE
c.name=?
');
$stmt->execute( array('cadetB') );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "uniforms of cadetB\n";
foreach( $stmt as $row ){
echo join(', ', $row), "\n";
}
// fetch cadets without uniforms
$query = '
SELECT
c.name
FROM
so_cadets as c
WHERE
NOT EXISTS(SELECT uniform_id FROM so_cadet_uniform as cxu WHERE c.id=cxu.cadet_id)
';
echo "cadets without uniforms\n";
foreach( $pdo->query($query, PDO::FETCH_ASSOC) as $row ){
echo join(', ', $row), "\n";
}
function setup($pdo) {
$pdo->exec('
CREATE TEMPORARY TABLE so_cadets (
id int auto_increment,
name varchar(32),
primary key(id)
)
');
$pdo->exec('
CREATE TEMPORARY TABLE so_uniforms (
id int auto_increment,
labelid varchar(32),
primary key(id),
unique key(labelid)
)
');
$pdo->exec('
CREATE TEMPORARY TABLE so_cadet_uniform (
cadet_id int,
uniform_id int,
primary key(cadet_id,uniform_id)
)
');
$stmt = $pdo->prepare('INSERT INTO so_cadets (name) VALUES (?)');
foreach( range('A','F') as $c ) {
$stmt->execute( array('cadet'.$c));
}
$stmt = $pdo->prepare('INSERT INTO so_uniforms (labelid) VALUES (?)');
foreach( range('K','Z') as $c ) {
$stmt->execute( array('label'.$c));
}
$stmt = $pdo->prepare('INSERT INTO so_cadet_uniform (cadet_id,uniform_id) VALUES (?,?)');
$cadetHasUniforms = array(
1=>array(1,2,3), // <- cadetA
2=>array(7,9), // <- cadetB
3=>array(8,5,4), // <- cadetC
// 4=>array() <- cadetD, no entry, no uniforms
5=>array(10,13,15) // <- cadetE
// <- cadetE, no entry, no uniforms
);
foreach( $cadetHasUniforms as $cadetId=>$uniformIds ) {
foreach( $uniformIds as $uid ) {
$stmt->execute(array($cadetId, $uid));
}
}
}
prints
uniforms of cadetB
cadetB, 7, labelQ
cadetB, 9, labelS
cadets without uniforms
cadetD
cadetF