My problem is:
I am joining tables together, and some tables have multiple data which I should fetch, but my JSON object only retrieves one. I think the reason for this is because the while loop loops through my main table aswell, fetches everything and stops looping, considering there is nothing left to loop through (I fetch my data based on my id in my database and these are auto_incremented etc).
So my question would be:
How can I loop through my main table (once), but keep on looping through the joined tables and insert these values in their 'own' array?
this is what I have right now:
$sqli = "SELECT event.*, typex.id, typex.type
FROM event
JOIN typex ON event.id = typex.id
WHERE event.id = ?";
mysqli_stmt_bind_param($stmt, 's', $editID); //fetch data based on ID
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data['all'] = array($row);
$data['type'] = array($row['type']);
}
//Echo data as JSON
echo json_encode($data);
So to give you an idea:
$data['all'] is the array which will hold all $row (this is so I can easily access columns from my main table)
$data['type'] however should only hold data from the table: typex (typex is a joined table).
an example:
You have a main table called: stack and a table you joined called: typex.
You want to insert all the rows with id number 5 from the table stack in the array $data['all'], considering the main table has an auto_increment on the id and unique, it will loop once... but now comes the part I fail at and need your help:
In your joined table: typex you have 2 rows with id number 5. these 2 rows should be fetched and inserted in the array $data['type']. How could this be achieved?
$data['all'] = array($row);
$data['type'] = array($row['type']);
This will always set the last $row's result, if you need all of the rows, you will need to do it like this:
$data[] = array('all'=>$row,'type'=>$row['type']);
Now each item of $data is an array with 2 keys, all and type
A few things to change here:
First in the query, as both the event and typex tables have an id column you will need an alias on one of them so you can distinguish between them, so I did that on typex.event also just in case.
$sqli = "SELECT event.*, typex.id as typex_id, typex.type as typex_type
FROM event
JOIN typex ON event.id = typex.id
WHERE event.id = ?";
Here I have amended the code to use the OO mysqli as its a whole lot easier to read
$stmt->bind_param('s', $editID);
$stmt->execute();
$result = $stmt->get_result();
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
$data = array();
$last_event = 0;
while ($row = $result->fetch_assoc()) {
if ( $last_event != $row['id'] ) {
$data['all'] = array($row);
$last_event = $row['id'];
}
$data['type'] = array('type' => $row['typex_type'], 'id' => $row['typex_id'] );
}
//Echo data as JSON
echo json_encode($data);
}
Related
I have created an array, it is used to fetch data from MySQL server.
$ids = array(249853, 245549, 249851, 245552, 245551, 249854, 245550, 282445, 261747, 249852, 222398, 248072, 248390, 272473, 219212, 234140, 249815, 241089, 271940, 274940);
$sorted_ids = implode($ids, ",");
Fetched data using $sorted_ids which is ID to retrieve, but it is retrieved data by ID ascending order
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids})";
$result = mysqli_query($connection, $sql);
I have tried using == but it is showing only indexes matched records others not.
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
if( $ids[$i] == $row['ID'] ) {
echo $row['ID']."<br>";
$i++;
}
}
It is showing records if both indexes matched not other records.
How can I display records by $ids array list ?
Easiest way to do what you want is to the order it within your SQL
$sql = "SELECT ID, number FROM table WHERE ID IN ({$sorted_ids}) ORDER BY FIELD(id, {$sorted_ids})";
Should do the trick
I would like to merge the results of two select statements and return one single JSON response. Basically, I want to return id, name, company, and email for every record found, but also return the signature column if the ticket matches the POST data.
Also, is it possible to remove any duplicate records in the final array?
$selectTable = "tickets_info";
$selectColumns = "id, name, company, email";
$stmt = $conn->prepare("SELECT $selectColumns FROM $selectTable WHERE created BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW() ORDER BY id DESC");
$stmt->execute();
if (isset($_POST['ticket'])) {
$stmt2 = $conn->prepare("SELECT signature FROM tickets_info WHERE ticket = ?");
$stmt2->execute(array($_POST['ticket']));
}
$results = $stmt->fetchAll();
if (isset($_POST['ticket'])) {
$results = $stmt2->fetchAll();
}
if ($results) {
header("Content-Type: application/json");
echo json_encode($results);
}
I would loop through the query response with something along these lines:
$stmt = $conn->prepare("SELECT id, name, company, email, signature, ticket FROM tickets_info WHERE created BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW() ORDER BY id DESC");
$stmt->execute() ;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$response[$i]['id'] = $row['id'] ;
$response[$i]['name'] = $row['name'] ;
$response[$i]['company'] = $row['company'] ;
$response[$i]['email'] = $row['email'] ;
if ($row['ticket'] == $_POST['ticket']) $response[$i]['signature'] = $row['signature'] ;
else $response[$i]['signature'] = NULL ;
$i++ ;
}
header("Content-Type: application/json");
echo json_encode($response);
You only do one SQL query and loop through the response once. If that row matches the AJAX ticket query, we add the signature to the array of objects. If not, we set the signature value to null.
The right way to do is use Join . If you don't want to do it with join you can first put the results in two different arrays. then merge those two seperate arrays and then filter any duplicate arrays.
Remember you want to have the same keys for both Sql Queries.
I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}
I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.
This is my database:
This is the query:
SELECT * FROM users
Now when I do this:
$query = $connection->query($_GET['query']); // SELECT * FROM users
print_r($query->fetch_assoc());
I get this as output:
Array (
[id] => 3
[username] => karel )
Why does it not output id 4 and username ccscs?
When I a while loop:
while($row = $query->fetch_assoc()){
print_r($row);
}
This is happening because you don't give any order to your query so it automatically get first record. If you want to return last record you can order by id desc as follow
SELECT * FROM users ORDER BY id DESC
If you instead need to retrieve all records you will need to loop throw your records
while($row = $query->fetch_assoc())
{
print_r($row);
}
Based on new op info i would not fetch twice but one as follow
$fields = array();
while($row = $query->fetch_assoc())
{
print_r($row);
$fields[] = $row;
}
fetch_assoc() retrieves a single row from a result set. See here.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
You should use something like this :
while($row = $query->fetch_assoc()){
print_r($row);
}
That's because fetch_assoc() just fetches one row.
To get each row you can do it like this:
while($row = $query->fetch_assoc()){
print_r($row);
}