Insert array into SQL database - php

I have an array of data that I would like to insert into my SQL database (table), I then want to be able to fetch it as an array in a separate file. I have no idea how to put it in as an array and get it back out as an array
This is for a contract, I have already tried inserting it as a string and then getting it out as an array but that doesn't work
$added = $_POST['added']; // this is the array
foreach ($added as $addedArr){
}
and I tried inserting $addedArr
That's the only code i can really show, I'm very stuck.

Using PDO (guide), for example, you could execute a query with an array, giving you a few options.
One such option would be to execute numerous queries with each sub-array, such as:
foreach ($arrays as $array) {
$query = $database->prepare('SELECT name, color, calories FROM fruit WHERE calories < ? AND color = ?');
$query->execute($array);
}
Another option would be to flatten out your array and do a multi line query like so:
$flat_array = []; //The array that will contain all the values of the main array of data
$query = 'insert into fruit (name, color, calories) values '; //Build the base query
foreach ($arrays as $array) {
$query .= '(?, ?, ?),'; //Add in binding points to the query
foreach ($array as $value) $flat_array[] = $value; //Add each value of each sub-array to to the top level of the new array
}
$query = $database->prepare(substr($query, 0, -1)); //Prepare the query, after removing the last comma
$query->execute($flat_array); //Execute the query with the new, flat array of values
You would then be able to pull out the data into an associative array later on with that same guide.

Related

Why PHP Mysql query inside a foreach loop always returns the first result from database?

I'm trying to run a MYSQL query inside a foreach loop.
here's the scenario:
I have a comma separated string with some names in it.
I use explode() and foreach() to get the separate values/names from this comma separated string.
Then I need to search mysql database for each of these values/names that I get from this string and if that value exists in the database, I then get its ID and create a new recrord in another table in the database.
However, when I run my code, I only get the ID of the first instance from the comma separated string.
my mysql database looks like this:
id category_name
3 Hotel
4 Restaurants
This is my code:
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
///i do the explode and foreach here///
$arrs = explode(',', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
}
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>;
}
so when the i run my code, I get the ID of the Hotel twice like so:
3
3
I'm expecting it to be like below based on what I have in MYSQL:
3
4
Could someone please advice on this issue?
First of all such things should be done using prepared statements. Not only it is easier and faster, but also more secure. Remember to always use prepared statements.
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
$stmt = $db_conx->prepare('SELECT * FROM categories WHERE category_name=?');
$stmt->bind_param('s', $cat);
foreach(explode(',', $biz_cat) as $cat){
$cat = trim($cat); // remove extra spaces at the beginning/end
$stmt->execute();
// we fetch a single row, but if you expect multiple rows for each category name, then you should loop on the $stmt->get_result()
$row99 = $stmt->get_result()->fetch_assoc();
// echo it in the loop or save it in the array for later use
echo $row99['id'];
}
In the example here I prepare a statement and bind a variable $cat. I then explode the string into an array on which I loop straight away. In each iteration I execute my statement, which in turn produces a result. Since you seem to be interested only in the first row returned, we do not need to loop on the result, we can ask for the array immediately. If you would like to loop just replace
$row99 = $stmt->get_result()->fetch_assoc();
with
foreach($stmt->get_result() as $row99) {
echo $row99['id'];
}
Once you get the id in the array, you can either print it out or save it into an array for later use.
As of now, you are re-assigning a new value to scalar variable $catIDS for each record returned by the query, then you echo it one you are done looping. You would need to put the echo/insert logic inside the loop (or maybe store the values in array).
Another thing to note is that you are splitting with , (a single comma), but you have a space between the two words. As a result, the second value (Restaurant) starts with a space, which will cause the query to return an empty resultset. You probably want to split with , (a comma followed by a space).
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(', ', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>';
}
}
The code below can do what you need.
Update INSERT YOUR NEW DATA HERE
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(',', $biz_cat);
foreach ($arrs as $arr) {
$query99 = mysqli_query($db_conx, "SELECT * FROM categories WHERE category_name='$arr'");
while ($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)) {
$catIDS = $row99['id'];
// INSERT YOUR NEW DATA HERE
echo $catIDS . '<br/>';
}
}

php dynamic POST[] values

I have this sql statement that gets user input from a form and stores the values in the database
foreach ($_POST["name"] as $key => $name) {
$sql = "INSERT INTO test_table(name,price) VALUES ('".$name."','".$_POST["price"]."')";
$mysqli->query($sql);
}
In my database, I get the correct name value but on the price field I get an array. Is there a way to get the value of the POST['price']?
you need to loop through the price too
If you are getting values from a single form do you need to pass them individually
you can create an array like this
$form_field = array($_POST["name"], $_POST["price"]);
foreach($form_field as $field => $value){
$sql = "INSERT INTO test_table(name,price) VALUES ('".$value[0]."','".$value[1]."')";
$mysqli->query($sql);
}
Try this out and see

Insert an array with multiple values, some of which are an array on its own to database

ISSUE
Hello, I have multiple PHP Arrays with multiple values that I am inserting to a SQL database from an XML file. Some of those values are an array on its own (Multi-dimensional array) but the value only gets stored as "Array", none of the sub-values get passed.
EXAMPLE ARRAY
[0] => Array
(
[A] => This is the Title
[B] => This is the Description
[C] => Array
(
[0] => Value 1
[1] => Value 2
[2] => Value 3
)
)
I have no problems inserting single values, so A and B will get inserted without a problem. But C will only get inserted as "Array".
INSERTION CODE
// This is the PHP array that contains multiple items
$Items
// There can be multiple Arrays in this XML so i have to loop through each one
foreach($Items as $Item => $value) {
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$value[A]', '$value[B]', '$value[C]');");
}
I want to serialize the [C] and put it in a single column. But if i do it in the foreach loop like this serialize("$value[C]") only "Array" gets passed to the value. I am a bit lost.
I will appreciate any help I can get.
Check each value as an array. If yes, serialize it else use as it is. Check below code, it might help you
// This is the PHP array that contains multiple items
$Items
// There can be multiple Arrays in this XML so i have to loop through each one
foreach($Items as $Item => $value) {
$A = is_array($value[A]) ? serialize($value[A]) : $value[A];
$B = is_array($value[B]) ? serialize($value[B]) : $value[B];
$C = is_array($value[C]) ? serialize($value[C]) : $value[C];
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$A', '$B', '$C');");
$A=$B=$C='';
}
Make empty temporary variables each time to hold new values.
The easiest and fastest way to serialize (and de-serialize later when needed) is using JSON. Your query would then become:
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$value[A]', '$value[B]', '" . json_encode($value[C]) . "');");
You should use prepared statement for mysqli and json_encode to serialize values:
foreach($Items as $Item => $value) {
$stmt = $mysqli->prepare("INSERT INTO database_name (A, B, C)
VALUES (? , ?, ?)")
$stmt->bind_param("sss", json_encode($value[A]), json_encode($value[B]), json_encode($value[C]));
$stmt->execute();
or if you are sure that only C value is array:
foreach($Items as $Item => $value) {
$stmt = $mysqli->prepare("INSERT INTO database_name (A, B, C)
VALUES (? , ?, ?)")
$stmt->bind_param("sss", $value[A], $value[B], json_encode($value[C]));
$stmt->execute();
You are referencing the Array object when call $value[C]
Loop over the [C] to get its contents:
foreach($items as $item) {
foreach($item as $itemDeep) {
// do stuff
}
}

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

How to bind mysqli parameters using loop and store results in array?

$genre = array(
'Action',
'Adventure',
'Fantasy'
);
$selectGenre_sql = 'SELECT genreID FROM genres WHERE dbGenre = ?';
if ($stmt->prepare($selectGenre_sql)) {
// bind the query parameters
$stmt->bind_param('s', $genre);
// bind the results to variables
$stmt->bind_result($genres);
// execute the query
$stmt->execute();
$array1 = array();
while ($stmt->fetch()) {
$array1[] = $genres;
}
}
The code above gets the value from genreID when dbGenre is equal to $genre. And then store the results in an array. But it's not working because $genre is an array, so I need to loop through it to get a different value from genreID each time.
The 'genres' table contains two columns: genreID (INT) and dbGenre (VARCHAR)
I just need each genreID (that is a number)... Let's say when dbGenre is equal to Action, then store the genreID in an array1, and then loop the $genre array to get the genreID for the next value and store it again in array1.
How can I fix it?
You can't bind an array to an SQL parameter. You can use a parameter in SQL in place of a single literal value. Not a list of values, or an expression, or a column name or table name.
To solve the task in your case, you can use either of two solutions:
First solution: loop over $genre array, bind each value one at a time and execute the SQL query for each value.
$stmt->prepare($selectGenre_sql);
$genre = array();
foreach ($gengre as $genreID) {
$stmt->bind_param('s', $genreID);
$stmt->execute();
$stmt->bind_result($genres);
while ($stmt->fetch()) {
$genre[] = $genres;
}
}
Second solution: execute the query once, with multiple parameters, one for each value in the array. This requires some tricky code to build a variable number of ? placeholders in the SQL query, separated by commas.
$selectGenre_sql = 'SELECT genreID FROM genres WHERE dbGenre IN ('
. join(',', array_fill(0, count($genre), '?')) . ')';
Also you need to get tricky calling bind_param() with a variable number of arguments based on the elements in your $genre array:
$stmt->prepare($selectGenre_sql);
$temp = array();
foreach ($genre as $key => $value) {
$temp[] = &$genre[$key];
}
array_unshift($genre, str_repeat('i', count($genre)));
call_user_func_array(array($stmt, 'bind_param'), $genre);
$stmt->execute();
$stmt->bind_result($genres);
$array1 = array();
while ($stmt->fetch()) {
$array1[] = $genres;
}
You might want to consider using PDO_MYSQL because it's easier to bind parameters from an array. The MySQLi interface is pretty awkward for this case.
A few things.
Could it be is't because your overwriting the $genre var, try changeing it to $genreArray in the sedond case?
Make sure that the database is actually returning things (try it in phpMyAdmin or something similar)
Try processing like this:
.
$genreId = -1;
$stmt->bind_results($genreId);
$stmt->execute();
while($stmt->fetch()){
$genreArray[] = $genreId;
}

Categories