PHP insert the array values into mysql - php

I had a problem inserting arrays into a MySQL database. I think found out that I cannot insert an array into columns of the table, and I should separate the values of the array and then do the insert action. But I don't know how to separate the values and insert those values. Should I separate the values and not use array?
Also I would like to create the table to shows all values(number1-10) of db stored.
Thanks for everyone!
Here's my codes below:
$varNum = array('1','2','3','4','5','6','7','8','9','10');
//an array showed in the selection box
<form action="testing_Rand.php" method="post">
<p><b><center>Choose an amount of random numbers in the selection box</center></b></p>
<p>
<select name="selectNum">
<?php
foreach($varNum as $key => $value):
echo '<option value="'.$key.'">'.$value.'</option>';
endforeach;
?>
</select>
</p>
<center><input type="Submit" value="submit"></center>
</form>
//A POST function to generate the random numbers
//do post function
if(isset($_POST["selectNum"]) ){
$arrayRand=intval($_POST["selectNum"]);
for($i=0;$i<=$arrayRand;$i++){
$varNum[$i]=rand(1,10000);
}
var_dump($varNum); //show results
$newRand = "INSERT INTO testing_Rand (number1, number2, number3, number4, number5, number6, number7, number8, number9, number10) VALUES ('$varNum')";
mysql_query($newRand);
}
//show mysql database results
$sqlDBrand = "SELECT id, number1, number2, number3, number4, number5, number6, number7, number8, number9, number10 FROM rand.testing";
$result = mysql_query($sqlDBrand) or die('MySQL query error');
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['number1'];
echo $row['number2'];
echo $row['number3'];
echo $row['number4'];
echo $row['number5'];
echo $row['number6'];
echo $row['number7'];
echo $row['number8'];
echo $row['number9'];
echo $row['number10'];
}

i think this may help you,
first make a string $sql and then use it in mysql_query()
$sql="INSERT INTO rand.testing (number1, number2, number3, number4, number5, number6, number7, number8, number9, number10) VALUES (";
$sql.=implode(',', $varNum);
$sql.=")";
mysql_query($sql);

It is depending on your Data and your Goal.
Take a look at the function implode:
$arr = [1,2,3,4,5];
$data = implode ('|', [1,2,3,4,5]) //1|2|3|4|5
$arr = explode('|', $data); //Converted back
http://www.php.net/manual/de/function.implode.php
If you need it searchable, considering a serialization to XML
$arr = [1,2,3,4,5];
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($arr, array ($xml, 'addChild'));
https://stackoverflow.com/a/1397164/2441442
If you need it not searchable, you can also take a look at serialize
$arr = [1,2,3,4,5];
$data = serialize($arr);
unserialize($data);
http://php.net/manual/de/function.serialize.php

Going back a stage, you have a table with a fixed number of columns but a variable number of fields of data to store. This is generally a bad idea.
It would be better to split this into 2 tables. One just stores something to identify the group of numbers, and another table that has several rows for each group of numbers; one row per random number per group.
This is a basic part of normalisation of data.
You could insert the to the 2 tables and grab the values with something like this:-
<?php
//A POST function to generate the random numbers
//do post function
if(isset($_POST["selectNum"]) )
{
$arrayRand=intval($_POST["selectNum"]);
for($i=0;$i<=$arrayRand;$i++)
{
$varNum[$i]=rand(1,10000);
}
if (count($varNum))
{
var_dump($varNum); //show results
$newRand = "INSERT INTO testing_rand (id) VALUES(NULL)";
mysql_query($newRand);
$inserted_id = mysql_insert_id ();
$newRand = "INSERT INTO testing_rand_numbers (rand_id, number) VALUES($inserted_id, ".implode("),($inserted_id, ", $varNum).")";
}
}
//show mysql database results
$sqlDBrand = "SELECT id, GROUP_CONCAT(b.number) AS all_numbers FROM testing_rand a LEFT OUTER JOIN testing_rand_numbers b ON a.id = b.rand_id";
$result = mysql_query($sqlDBrand) or die('MySQL query error');
while($row = mysql_fetch_array($result))
{
echo $row['id'];
echo $row['all_numbers'];
}
?>

Related

passing multidimensional array to mysql using generated input fields

<?php
if (isset ($_POST['submit'])){
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
$query="INSERT INTO athletes (name, sports) VALUES ('".$data."')";
$result = mysqli_query($dbc, $query);
mysqli_free_result( $result);
}
?>
getting error array to string conversion.
hot do i pass that in the database in separate rows.
the output is working wonderfully when i dump just the way i want it but i cant seem to get it passed to the database.
I think you don't need to make multidimensional array name[][], you just use name[] so in your PHP code it is just like,
$name=$_POST['name'];
$sports=$_POST['sports'];
$data=array();
for($x=0,$l=count($sports); $x<$l; $x++){
$myArray = explode(',', $name[$x]);// you can use your own filter for names
foreach($myArray as $nm){
$data[]=array('name'=>$nm,'sports'=>$sports[$x]);
}
}
var_dump($data);
Demo
You can change $data while inserting in database like,
$data[]='("'.trim($nm).'","'.trim($sports[$x]).'")';
And after your loop ends you can create query like,
$sql ="INSERT INTO <table> (name,sports) VALUES ".implode(',',$data);
Demo with Query
You need to create separate array from post value for each row.
http://sandbox.onlinephpfunctions.com/code/c8aede27dc5675a8715be328dec6c5ea4c669522

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

Echo the results of query based on its index

This is pretty basic but I can't seem to get it to work
I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the first result of this query with
<?php echo $row_people['name']; ?>
I could also create a loop and echo all the results.
But I really want to echo the results individually based on its index.
I have tried this, but it does not work.
<?php echo $row_people['name'][2]; ?>
Thanks for your help.
You can fetch them by their index using a WHERE clause.
$people = sprintf("SELECT name FROM people WHERE index='%d'", $index);
If you want to query all rows, you could store them into an array while looping over them:
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$totalRows_people = mysql_num_rows($people);
$rows_people = array();
while($row_people = mysql_fetch_assoc($people))
{
$rows_people[] = $row_people;
}
You might want to add the primary key to the returned fields and use it as the array index probably.
You can ORDER them by their index and then use a loop.
$people = "SELECT name FROM people ORDER by index";
You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2:
mysql_data_seek($people, 2);
$row_people = mysql_fetch_assoc($people);
echo $row_people['name'];
If you're doing this a lot it will be easier to gather all the rows together in a single array at the start:
$data = array();
while ($row = mysql_fetch_assoc($people)) $data[] = $row;
This way you can fetch any cells in the results trivially:
echo $data[2]['name'];

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Mysql fetch value transfer to an array

Is it possible to transfer a fetch value to an array?
For example in my database table I have a column named vehicle, and inside that column, it contains:
vehicle1
vehicle2
vehicle3
All of that in one array.
Now is it possible to transfer it to an array? (array())?
Another question:
How can I echo it separately?
vehicle1
vehicle2
vehicle3
are all in one mysql array, how can I echo it one by one? Because if I echo the array the result would be the three vehicles. What I'm asking is that how can I echo the array that the result would be vehicle1 and if I echo it again, vehicle2. and so on.
$vehicles = array();
$sql = "SELECT `vehicle` FROM `table` WHERE 1";
$result = mysql_query($sql);
if ($result) {
while (($row = mysql_fetch_array($result)) !== false) {
$vehicles[] = $row['vehicle'];
// or
// $vehicles[] = $row; // store all columns in vehicle array
}
}
foreach($vehicles as $vehicle) {
echo "{$vehicle}<br />\n";
}
You can also create an array of arrays to store multiple details from the result of your queries.

Categories