passing multidimensional array to mysql using generated input fields - php

<?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

Related

PHP insert the array values into mysql

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'];
}
?>

Store Session Array in Database

I have the array-ed session....
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
and I want to store them in my database...
$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);
After Saving, my database (tblpeople) shows the following values:
DateTimePosted: 2014-01-03 16:23:02
first: Array[0],Array[0]
second: Array[1],Array[1]
third: Array[2],Array[2]
Instead, I want my output to be...
DateTimePosted: 2014-01-03 16:23:02
first: 11,35
second: 15,42
third: 26,10
What's wrong?
To expand multidimensional arrays in a string, you need to wrap them in curly braces:
$que = "Insert into tblpeople (DateTimePosted, first, second, third)
VALUES(now(),
'{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
'{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
'{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";
You also had some extra parentheses in the values.
However, this seems like a pretty strange way to store data into a database. Why do you have two values separated by commas in each column, rather than splitting each into separate columns? And why are you storing array elements into different columns, rather than using separate tables with each value in a row?
use this function
$x=serialize($_SESSION['Names']);
it return a string that you can save any where
and this function reverse it
$_SESSION['Names']=unserialize($x);
Try this
<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'Names' => $refNumber,
'Location' => $partIds[$index]
);
}
print_r($combined);
$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);
$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);
?>

How to print only index of an array

Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}

Inserting an array into different rows in database

I'm having an issue inserting an array into my database. When i tried implode, it all inserted all the arrays into one row. What i intend to achieve is to insert a single array into different rows.
In the array i have fields such as bag,shoes,cloths and i wish to insert into one table but different rows.
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$final = implode(',',$all_subjects_to_insert);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$final')";
I'll appreciate any help i get. Thanks.
if $all_subjects_to_insert is multidimensional array then what you are looking for is
foreach($all_subjects_to_insert as $value)
{
$query = "INSERT INTO #__sch_subject (subject) VALUES ('{$value}')";
mysql_query($query);
}
Reference
Thanks everyone. Its now working. The separator for the implode function was incorrect. Here is the working code
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$inserted_values = implode("'),('",$all_subjects_to_insert);
print_r($finalvalues);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$inserted_values')";
With the separator the insert command looks like this
$query ="INSERT INTO #__sch_subject (Subject) VALUES ('a'),('b'),('c')";
Thanks for the help. I really appreciate.

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

Categories