Separate mysql_query from foreach validation check php - php

This is a snippet of my code. I essentially I have a new array I want to insert into tablename, but before I do that I validate the new stat figures against the old ones, confirm they are numeric and insert into a new row.
I realise what I have done, the mysql_query is inside the foreach loop, it inserts 5 rows all the same. I want it to only insert 1 new row.
How Do I take the mysql_query outside the loop yet keep the validation that the foreach loop provides before attempting to insert a new row?
foreach ($statnumber as $element) {
if ($statnumber != $LastWeeksStats && is_numeric($element)) {
mysql_query("INSERT INTO tablename (idproducts, stat1, stat2, stat3, stat4, stat5, superstat1) VALUES('8', '$statnumber[0]', '$statnumber[1]', '$statnumber[2]', '$statnumber[3]', '$statnumber[4]', '$statnumber[5]')") or die(mysql_error());
} else {
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}}
mysql_close();

I would remove the elements that fail the check from the array then have the mysql statement outside the loop at the end. Use unset but you have to keep track of what keys to unset like this:
foreach ($statnumber as $key => $element) {
if($statnumber != $LastWeeksStats && is_numeric($element)) {
//do nothing because it is valid
} else {
//remove that element from the array
unset($statnumber[$key]);
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}
}
//now only valid data is in the array and you can use a mysql query
You will have to update the mysql query based on how many elements are actually in the array at the end like so:
foreach($statnumber as $key => $element) {
$keys[] = "stat$key";
$elements[] = "'$element'";
}
$keystring = implode(",",$keys);
$elementstring = implode(",",$elements);
mysql_query("INSERT INTO tablename (idproducts, $keystring, superstat1) VALUES('8', $elementstring)") or die(mysql_error());

Related

Multidimensional array values not inserted through PDO loop

I have a dynamic HTML form with three fields (item, number, cost). Users can add as many rows as they need. Because of this, I have set the fields names as item[], number[], cost[] in order to loop through the post and insert the values in the DB.
I have verified that the values are posted correctly up correctly through vardump, and I have checked that the following loop is picking up the values (both key and value) through printr. (and also simply echoing $value1).
foreach ($_POST as $field => $value) {
foreach($value as $field1 => $value1){
echo $field . ':' . $value1 . '</br>' ;
}
};
However, if I try insert passing the values to execute, nothing happens (no data is inserted and I get no error message).
if($_POST['submit']){
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO invoice (item, number, cost) VALUES (?,?,?);');
foreach ($_POST as $item => $value) {
foreach($value as $item1 => $value1){
$stmt->execute($value1);
}
}
$pdo->commit();
}
catch (Exception $e){
$pdo->rollback();
throw $e;
}
}
I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?
I have tried:
https://phpdelusions.net/pdo_examples/insert#multiple
PDO insert statement with loop through $_POST array
PDO insert array values Insert multiple rows using form and PDO
Need php pdo implode arrays and insert multiple rows in mysql
As your $_POST array contains columns you need to get values from the corresponding cells, i.e. for the first row you need items[0], number[0] and cell[0] and so on. So iterate over the first column, get the index and use that index for the other two
foreach ($_POST['item'] as $i => $item) {
$stmt->execute([$item, $_POST['number'][$i], $_POST['cost'][$i]]);
}

PHP Insert into table not creating new line of data

I'm new to PHP and I'm trying to insert data from a nested array into a database. I'm noticing though that only the last key:value gets put in (seems almost as if everything else before gets overwritten). How do I get a new line of each data so everything gets put in?
$tmpArray = array(array("one" => abc, "two" => def), array("one" => ghi, "two" => jkl));
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
}
}
}
For simplicty, all I'm trying to do is to get "one" and "abc" put into alpha and beta. Then have another row of the table input "one" and "ghi". But when I run the code, all I get is "one" and "ghi". When I put an echo statement though, all the correct stuff gets printed. Just don't understand why they aren't getting input into my tables.
What am I doing wrong? Thanks!
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
This line overwrites the contents of the variable $sql every time it is called. You need to concatenate your strings together instead:
$sql = '';
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql .= "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value'); ";
}
}
}
Still better, as suggested in a comment, would be to simply execute the query directly rather than store it in a variable. Then you don't have to concatenate the strings together, nor do you have to enable multiple statements in a single MSQLI call.

Php - Array to string conversion

I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".
I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result[0] as $value)
{
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
So, with the index, it does work. But I need all records, not just one.
I appreciate every comment and help!
I would start with a nested loop. I also wonder if you want a table for every value
$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();
if (is_array($result) || is_object($result))
{
foreach ($result as $row){ //Go through every row in the result
echo('<table>');
foreach ($row as $value){ //Go through every value in the row
echo "<tr><td>'$value'</td></tr>";
}
echo('</table>');
}
}
This will print every row as a new table, but you can search out the variation you want.
A nested foreach loop should work.
foreach ($result as $values)
{
foreach ($values as $value) {
echo "<table><tr><td>'$value'</td></tr></table>";
}
}
An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.
Quick example:
$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
$output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";
Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.

How to stop a while loop from running infinatly by making it stop when there are no more values in the array

I am trying to make pull key => value pairs out of an array by using a do { ....} while {there are values left inside the array.
I am using a function to query mysql for and then to insert all the values inside an array
function table_array($query) {
$table_array = array();
$data_fetched = false;
while ($array = mysql_fetch_assoc($query)) {
if (!$data_fetched) {
foreach ($array as $key => $value) {
$table_array[$key] = $value;
//$data_fetched = true;
}
}
}
return $table_array;
}
and then i am using another loop to extract the data from the array
function get_table($table_array) {
$header_written = false;
echo "<table border=1>";
if ($table_array) {
do {
echo "<tr>";
foreach ($table_array as $columns => $values) {
echo "<td> {$values} </td>";
}
echo "</tr>";
}while ($table_array);
}
echo "</table>";
}
However this causing my loop to run infinitely , why can't i use it just as though i would be doing while mysql_fetch_assoc is true.
I tried using a flag but that will stop it running after only one record is being extracted.
What you really need here are two foreach loops. The outer iterates over rows, and the inner iterates over columns:
echo "<table>";
// Iterates over rows
foreach ($table_array as $row) {
echo "<tr>";
// Iterates over columns (table cells)
foreach ($row as $col=>$value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
Though your fetching process works, it can be simplified and improved. You don't need a foreach to assign columns to your $table_array. You can simply append the whole fetched row using the [] syntax. Not sure what the purpose of $data_fetched was, so I removed that as well
while ($array = mysql_fetch_assoc($query)) {
// Use the [] syntax to append the whole row onto $table_array
// No need to add each column of the fetched row separately
$table_array[] = $array;
}
Finally, the reason it didn't work the way you setup your do-while is that iterating over a regular array is not similar to fetching from a MySQL result set. The fetch calls will eventually return FALSE when no rows remain. Unless you are actively removing elements from an array while iterating over it, and eventually deleting the empty array, it will always evaluate to a boolean TRUE.
You need to use either foreach($array as $key => $value){ ... } or do{ ... } while ($array).
You should not use both, as you only have one set of data to loop over. I would stick with foreach as it is safer, and can do exactly what you need.
If you feel you need to use a do/while, then you need to pop a value off the $table_array each time you are inside the loop. This way, the $table_array will become empty at some point. Currently, in your code, the $table_array is always full so the while loop continues endlessly.

Insert php nested array into mysql table

what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}
You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array
Better way to insert thousands of data into DB is to use implode function implode
i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}

Categories