Insert multiple rows into mysql database (items separated by comma) - php

need help...!!!
i have 2000 number of values like (3458,1356,....n)
i want to post them from html input field as $_POST['roll']; along with few other columns which has similar values like board (dhaka,dhaka,dhaka) .. i want to insert them into database with php at once not one by one..
NOTE: i know there is a way to insert multiple rows but it will be time consuming to create that query for 2000 values.. so i want to use 2000 values at once with comma..
result should be like this
+---------+-------------+
| board | roll |
+---------+-------------+
| dhaka | 3456 |
| dhaka | 4574 |
| dhaka | 6357 |
| dhaka | 2467 |
+---------+-------------+
i am using this query to post single row at a time
$board = $_POST['board'];
$roll = $_POST['roll'];
$query = "INSERT INTO `host`.`result` (`board`, `roll`) VALUES ('$board','$roll') "

At first,
you can use php explode() function to make an php array. Then you INSERT your data using loop depending on Array size.
Code Example :
$roll = array();
$board = array();
$roll = (explode(",",$_POST['roll']));
$board = (explode(",",$_POST['board']));
$arraySize = sizeof($roll);
for($i=0; $i<$arraySize ; $i++){
$query = "INSERT INTO `host`.`result` (`board`, `roll`) VALUES ($board[$i],$roll[$i]) "
}

Related

PHP script looping string

I have a string, I need to put this information into a database.
I'm not sure of the best way to manipulate the string to use with an insert script. my skill level is very low. I've read a bit about looping but dont know how or where to begin.
Is there a better way to manipulate the string to make db insert easier?
Many thanks
<?php
$date = $_SESSION['date'];
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
/*
I have been trying to break it down in the following way.
$new = preg_split("[;]", $string);
$x1=(explode(',', $new[1]));
$x2=(explode(',', $new[2]));
I would like to insert it into the following table
INSERT INTO table ("date, team, name, driver, car
values
('$date' ,'$x1[0]', '$x1[1]', '$x1[2]', '$x1[3]'),
('$date' ,'$x2[0]', '$x2[1]', '$x2[2]', '$x2[3]')");
*/
Table
| date | team | name | driver | car |
---------------------------------------------------------
| cur | unallocated | SUSY.. | A | null |
| cur | unallocated | BERN...| R | null |
You can use below code to insert into your database table.
<?php
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
$arr = explode(';', $string);
foreach($arr as $row){
$arr_row = explode(',', trim($row)); // Converting each line to array which can be used as values.
print_r($arr_row);
// Write your insert statement into your database.
// e.g INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
}
Now you can use $arr_row[0], $arr_row[1] ... and so on to build your sql.

MySQL PHP select where "X,Y" is in X,Y,Z

How do I complete this code below? I am trying to select news from the database and the locations which can be 23,22,88,90 location codes. I know you can just do IN('23', '22', '88', '90') but the problem is, my locations are a string so it comes out like IN('23,22,88,90') I believe.
How do I expand on the string of locations and select all or any including the locations in the string? So in the database, newsLocations could be 22 23 22,90 23,80,90 90. If that makes sense? so if $locationstoGet has 22,88,90 only, it will get the newsLocation even if the result is just 88,90 without the 22.
$locationsToGet = '22,88';
$db->query("SELECT * FROM news WHERE newsLocation IN($locationstoGet)");
I hope I explained this alright.
I saw a response on another site here
So I will adapt the solution there to your scenario. Change locationsToGet into an array, and use the implode function to generate the right syntax for the IN Clause.
$locationsToGetArr = array('22','88');
$locations = "'".implode("','",$locationsToGetArr)."'"; //this should output '22','88'
$db->query("SELECT * FROM news WHERE newsLocation IN($locations)");
This solution is assuming your database structure is as such
+--------+--------------+
| news | newsLocation |
+--------+--------------+
| 1 | 88 |
| 1 | 22 |
| 2 | 22 |
| 2 | 88 |
+--------+--------------+
But if you are storing your data as the following instead
+--------+--------------+
| news | newsLocation |
+--------+--------------+
| 1 | 88,22 |
| 2 | 22,88 |
+--------+--------------+
You will not have much choice besides to select all from news table and have PHP filter the location. Not a very efficient method.
If your data is comma separated stored in databse column then you can use MYSQL FIND IN SET as per below example.
SELECT FIND_IN_SET('b','a,b,c,d');
OR you can try with regular expression in MYSQL but it will be too slow.
You can make an array of your locations and then populate your query string with the items from the array
$locations = '22,88';
$locationsToGetArray = explode(",", $locationToGet)
$query = "SELECT * FROM news WHERE newsLocation IN(";
for ($i = 0; $i < count($locationsToGetArray); $i++) {
$query .= $locationsToGetArray[$i];
if($i == (count($locationToGetArray) - 1)) $query.= ")";
else $query .= ",";
}
$db->query($query);

How can I get the sums of all the integers in a row of an SQL table with PHP?

I am currently making an attendance website. The data for attendance is stored like this...
+-----------------------------------------------+
| Name | 12/20/16 | 12/21/16 | 12/23/16 |
+-----------------------------------------------+
|Person1 | 1 | 0 | 1 |
|Person2 | 0 | 1 | 0 |
|Person3 | 1 | 1 | 1 |
+-----------------------------------------------+
If a person was there, then the date column for their row is marked as a "1". If they weren't there, then the date column for their row is marked as a "0".
I am trying to make a readout of how many days they were present.
How can I get a sum of all the values in the date columns for that specific person's row in PHP?
EDIT: I understand that it is a bad way of formatting the data. This is per the owners request. They have their mind set on it and won't listen to reason. They are thinking of SQL as an Excel file.
Since you can't refactor the database to work the only way to do this is
SELECT name, `12/20/16`+`12/21/16`+`12/23/16` as days_attended
FROM tablename
and yes every time you add a column you have to change your query.
You could make a dynamic query -- use the above as a template as to what that dynamic query would look like.
But you REALLY should refactor the database and make a view for your user to make them happy.
This is exactly why views exist.
Okay so with the help of some people in the comments, I have put together a working function to accomplish what I needed.
$ppl = mysqli_query($conn, "SELECT * FROM Attendance2016 WHERE name = '" . getSessionVal("Name") . "'");
$row = mysqli_fetch_array($ppl);
$loopMax = count($row);
$currentAtttendance = 0;
for($x = 0; $x < $loopMax; $x++){
if($row[$x] === "0"){
continue;
}else if($row[$x] === "1"){
$currentAtttendance = $currentAtttendance + 1;
}
}
return $currentAtttendance;

API-call JSON into MySQL

I'm working on a research project where we want to insert a JSON file (from an API-call) into a mysql database. I found multiple examples but I don't know where to begin because there are multiple objects and arrays. A second problem is that the columns and rows are separate arrays (I think?).
Our goal is to fill (daily, hourly, etc) a database that looks likes this (it is an example and we do have multiple items):
-----------------------------------
| Date | Value2 | Value3 | Value4 |
-----------------------------------
| 01-01-2015 | 123 | 1234 | 12345 |
-----------------------------------
| 02-01-2015 | 343443 | 4w3543422 | fref4rw4 |
-----------------------------------
| 03-01-2015 | 234422r | wrfrw3434 | 2432rfr42324 |
-----------------------------------
Question is how can I get those values from the JSON (which isn't static: sometimes there will be seven days, sometimes less and sometimes more)? Where to begin?
Code from #Marmik did the trick!
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c] [2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
I think using foreach loop after decoding the JSON to PHP Array it can be worked out.
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c][2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
And this SQL statement is created by JSON array's data.

How to display multiple rows of comma separated values from mysql db

I need your help with display of some comma separated enteries from my database.
My main table schema looks like this
|---|----------|-----------|----------------------------|
|id | tab1 | tab2 | tab3 |
|---|----------|-----------|----------------------------|
|1 | state1 | A-North | constA1,constA2,constA3 |
|2 | state2 | B-South | constB1,constB2,constB3 |
---------------------------------------------------------
Query I'm trying to make work
$query = mysql_query("SELECT * FROM `main` WHERE `tab1` = '$tab1'")
or die(mysql_error());
while($row=mysql_fetch_array($query)){
$tab3 = explode(",", $row['tab3']);
echo $tab3."<br>";
}
What I want to display from the database
A-North B-South
---------------------
constA1 constB1
constA2 constB2
constA3 constB3
Error I'm getting when I run that query is "Array" . When I run the same code from phpMyAdmin, I get the desired rows (result).
Explode gives you the results in an array so you'll want another loop that runs through the $tab3 array printing the result. See the definition from the PHP manual:
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
For example:
for ($i = 0; $i < sizeof($tab3); $i++) {
echo $tab3[$i].'<br />';
}
explode will return array using print_r($tab3) you can view the items and access it by
echo $tab[0];
echo $tab[1];
echo $tab[2];
etc.....
explode ($separator,$string) returns an array. You need to step through the array to create the table columns.
Also, as you want the data in two columns, create these separately as two separate tables and then include those into a single table as two separate cells
Finally, redesign your database table. You'll thank us in the end

Categories