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.
Related
I want to make a php web page which will query the mysql db and mysql might return more than 1 row.
I want to print those rows one after another.
$query = "SELECT * FROM tables WHERE name = 'table1';";
$req = mysqli_query($conn, $query);
$res = mysqli_fetch_assoc($req);
I want to print something like this
Poem_id | Poem_content | Poem_by | Poem_hotscore
------------ ----------------- ----------- -----------------
1 | Blah Bleh<br>B.| 4 | 5342.3920349
7 | Blah Bluu<br>F.| 4 | 5003.3920382
9 | Blerp Bloop Foo| 34 | 4300.7281209
while (($res = mysqli_fetch_assoc($req)) !== NULL)
echo $res["Poem_id"]." | ".$res["Poem_content"]."<br />"; // and so on
Please note that php array keys are case sensitive. So there's a difference between
$res["Poem_id"]
and
$res["poem_id"]
Also don't forget to use htmlentities().
I need some help from joining tables horizontally my tables are
+---------+---------+
| Candidates Table |
+---------+---------+
| can_id | Name |
+---------+---------+
| 1 | Liza |
| 2 | Sarah |
| 3 | Jane |
| | |
+---------+---------+
+---------+---------+
| Judges Table |
+---------+---------+
| id | Name |
+---------+---------+
| 1 | judge1 |
| 2 | judge2 |
| 3 | judge3 |
+-------------------+
+---------+---------------+--------+-------+
| Score Table |
+---------+-------+------------------------|
| sco_id | can_id| jud_id |crit_id |score|
+---------+--------+-----------------------+
| 1 | 1 | 2 | 1 | 87 |
| 2 | 1 | 3 | 1 | 89 |
| 3 | 1 | 1 | 1 | 80 |
+------------------------------------------+
I need an output of something like this one..
+---------+---------------+-------------+
| Score board |
+---------+---------+-------------------|
| Name | judge1 | judge2 | judge3 |
+---------+---------+-------------------|
| Liza | 80 | 87 | 89 |
|some data|some data|some data|some data|
|some data|some data|some data|some data|
+---------------------------------------+
notes: crit_id is criteria id from criteria table.
Normally I would use some joins and subqueries but my problems is I need the output dynamically where in if I add a new judges it will automatically generate a new column. I need at least 1 candidate data with all of the judges scores then just loop it with parameters on php to get the other candidates data something like
php loop start
<td>name</td>
<td>judge1 score</td>
<td>judge2 score</td>
php end loop
or if i could get the whole candidates table with judges score much better for me not to loop them per candidate
I've tried to research similar questions like
Concatenate more than two tables horizontally in SQL Server
I've tried to code myself but I got stuck with joining the judges..
SELECT s.sco_id,c.Name,c.Municipalities
FROM `tbl_scoring` s
LEFT JOIN tbl_candidates c ON c.`can_id` = s.`can_id`
WHERE s.can_id = 11
AND crit_id = 1
ORDER BY s.jud_id asc
I need a query that would generate dynamically depending on the number of judges either get candidate data with scores of judge then loop it on php or much way better if i get all the data without looping
Initialize the following arrays:
$judges = [];
$scores = [];
$candidates = [];
Then execute your query, and loop the results. Set those values for each iteration:
$judges[$row['jud_id']] = 1;
$candidates[$row['can_id']] = $row['Name'];
$scores[$row['can_id']][$row['jud_id']] = $row['score'];
Now you want to get the participant judges names, so let's run a SQL query:
$sql = 'SELECT Name FROM judges WHERE id IN (' . implode(',', array_keys($judges)) . ')';
And on every iteration set the judge's name in the $judges array:
$judges[$row['id']] = $row['Name'];
Then for the output:
echo '<tr>';
echo '<td>Name</td>';
ksort($judges);
foreach ($judges as $name) {
echo '<td>Judge: ' . $name . '</td>';
}
echo '</tr>';
foreach ($scores as $candidateId => $data) {
echo '<tr>';
echo "<td>$candidates[$candidateId]</td>";
ksort($data);
foreach ($data as $score) {
echo "<td>$score</td>";
}
echo '</tr>';
}
I used ksort on $judges and $data so the score will fit each judge.
first, we retrieve the judges' ids and name that exist on the score table.
$judges = [];
$query = "SELECT id, name FROM Judges WHERE id IN ( SELECT DISTINCT jud_id FROM Score )";
// execute the query and store the results in the $judges array.
we retrieve the candidates' ids and name that exist on the score table.
$candidates = [];
$query = "SELECT id FROM Candidate WHERE id IN ( SELECT DISTINCT can_id FROM Score )";
// execute the query and store the results in the $candidates array.
then, we join the candidate and score table.
$candidate_score = [];
$query = "SELECT Candidate.name, Candidate.id as candidate_id , Score.jud_id, Score.score FROM Candidate JOIN Score ON Score.can_id = Candidate.id";
// execute the query and store it in the $candidate_score array.
now, for each candidate, we fill its score on the $score_board array.
$score_board = [];
foreach ( $candidates as $candidat )
{
$score_board[$candidat] = [];
foreach ( $judges as $judge )
{
$judge_name = $judge['name'];
$judge_id = $judge['id'];
$score_board[$candidat][$judge_name] = get_judge_score($candidate_score,$candidat,$judge_id);
}
}
this is how the get_judge_score will work:
function get_judge_score ( $scores , $candidate , $judge )
{
$score_filtred = array_filter($scores, function ($score) use ($candidate,$judge) {
return $score['jud_id'] == $judge && $score['candidate_id'] = $candidate;
});
return count($score_filtred) > 0 ? $score_filtred[0]['score'] : 0;
}
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);
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]) "
}
I have a table that look like this:
Name | date1 | date2 | date3 | etc..
per1 | status1 | | status2 | etc
per4 | status2 | status3 | | etc
The number of the dates columns is not fixed. Their values can either be a status or they can be empty.
I want to access the data of the dates columns for each row separately and process the data.
The output I want to achieve:
Name | field1 | status1 | status2 | etc..
per1 | value | #ofstat1 | #ofstat2 | etc
So for I got, accessing the table at the beginning of the question:
$confirmed ="Confirmed";
$accepted ="Accepted";
while ($row = mysql_fetch_array($result)) {
$confirmed_cnt =0;
$accepted_cnt =0;
foreach ($row as $value) {
if (strcmp($value, $confirmed)) $confirmed_cnt++;
else if (strcmp($value, $accepted)) $accepted_cnt++;
}
print("<tr>");
print("<td>$row["Name"]</td>"); // name
print("<td>$confirmed</td>"); // confirmed
print("<td>$accepted</td>"); // accepted
print("</tr>");
}
As far as I know this should work, but for some reason it goes trough each column 2 times in a row.
Try mysql_fetch_assoc() or mysql_fetch_row() instead.
mysql_fetch_array() returns every column two times: as [1] and as ['fieldName']
Also, you have another error, replace your following line:
print("<td>$row["Name"]</td>"); // name
for this one:
print("<td>$row['Name']</td>"); // name