For each results- Mysql - JSON - php

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}

Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag

$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

Related

How to make a PHP page have two "column" regions?

Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}

How do I create a nested list inside of a while loop?

I'm having trouble trying to get a nested < ul > inside of a while loop. I'm not sure if this even possible so i'm open to alternatives.
Here's a quick image of what my database looks like and what i'm trying to achieve.
Here's my sql
SELECT *
FROM drinks_category, drinks_lookup, drinks
WHERE drinks.drink_id = drinks_lookup.drink_id
AND drinks_lookup.drinks_category_id = drinks_category.drinks_category_id
ORDER BY drinks_category.drinks_category_title
Here's my output php
$result = $conn->query($sql) or die(mysqli_error());
$last_category = 0;
while ($row = $result->fetch_assoc()) {
if($row['drinks_category_id'] != $last_category) {
echo "<h1>" . $row['drinks_category_title'] . "</h1>";
}
echo "<p>" . $row['drink_name'] . "</p>";
$last_category = $row['drinks_category_id'];
}
Im using mysqli and php. Thanks in advance!
Update your while loop to the following:
while ($row = $result->fetch_assoc()) {
if($row['drinks_category_id'] != $last_category) {
if($last_category != 0) echo '</ul>';
echo "<h1>" . $row['drinks_category_title'] . "</h1>";
echo "<ul>";
}
echo "<li>" . $row['drink_name'] . "</li>";
$last_category = $row['drinks_category_id'];
}
if($last_category != 0) echo "</ul>";
Instead of having 3 tables, you could just add a category_id to your drinks table, just to simplify things. Then you can do this:
SELECT drink_name, (SELECT drnk_category_title FROM drinks_category WHERE drink_category_id = drink_category // THE COLUMN I SUGGESTED //) AS title FROM drinks
And then you can loop the result and build the nodes you desire really easily
$result = $conn->query($sql) or die(mysqli_error());
$last_category = 0;
while ($row = $result->fetch_assoc()) {
if($row['drinks_category_id'] != $last_category) {
// close previous </ul>
if( $last_category != 0 ) echo "</ul>";
// new title
echo "<h1>" . $row['drinks_category_title'] . "</h1>";
// new <ul>
echo "<ul>";
$last_category = $row['drinks_category_id'];
}
echo "<li>" . $row['drink_name'] . "</li>";
}
// close last </ul>
if( $last_category != 0 ) echo "</ul>";

how to print out two arrays in php concatenating them

I have two arrays in my php that I want to print. I want them to be concatenated but I don't know how. The array for the $names prints but the description array "$desc" does not. is there any way to print both together?
$query = "SELECT eName FROM Events";
$query2 = "SELECT eDescription FROM Events";
$result = mysql_query($query);
$result2 = mysql_query($query2);
$names = array();
$desc = array();
echo "hello there people!" . $query . " ".$result;
for($i=0; $i<sizeof($result); $i++){
echo $result[$i] ."\n" . $result2[$i];
}
while($entry = mysql_fetch_row($result)){
$names[] = $entry[0];
}
while($entry2 = mysql_fetch_row($result2)){
$desc[] = $entry2[0];
}
echo "Which Event would you like to see?<br>";
$stop = count($names);
//echo $stop . "\n";
$i = 0;
print_r($names);
print_r($desc);
foreach($names as $value){
echo $value . " " . $desc[i] ."<br>";
$i++;
}
Why are you doing two queries to get data from the same source?
$sql = mysql_query("select `eName`, `eDescription` from `Events`");
while($row = mysql_fetch_assoc($sql)) {
echo $row['eName']." ".$row['eDescription']."<br />";
}
Much simpler.
Try this:
foreach($names as $key => $value){
echo $value . " " . $desc[$key] ."<br />";
}
As long as the array $key match, the information will be printed together.

How do I echo out something different when reached last row?

I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:
<?php
header("Content-type: application/json");
echo '{"points":[';
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";
$res = mysql_query($q) or die(mysql_error());
while ($point = mysql_fetch_assoc($res)) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
mysql_free_result($res);
echo ']}';
?>
Could you not use json_encode() instead, rather than hand-crafting the JSON?
$result = array();
//snip
while ($point = mysql_fetch_assoc($res)) {
$result[] = $point['lat'];
$result[] = $point['lon'];
$result[] = $point['temperature'];
}
//snip
header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Use a count query to get the number of rows to begin with.
$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);
Then introduce a conditional and a count decrease each time through...
while ($point = mysql_fetch_assoc($res)) {
$count = $count - 1;
if ($count == 1) {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
} else {
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
}
Json encode would probably be your best bet, but you could also use trim();
Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.
About the comma problem, I always target the first item instead of the last:
$first = true;
while ($point = mysql_fetch_assoc($res)) {
if ($first)
{
$first = false;
}
else
{
echo ",";
}
echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.
...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);
Then combine that with Scotts answer and you should be set.

help with php search

How would I do let the user know if there wasnt any rows found?
And if it finds (for example) 26 rows I want it to print that it found 26 hits (Your search for "hey" gave 26 results)
$name = mysql_real_escape_string($_POST['player_name']);
$q = mysql_query("SELECT * FROM players WHERE name LIKE '%$name%'");
while ($row = mysql_fetch_array($q)) {
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
Use mysql_num_rows:
$rowCount = mysql_num_rows($q);
if ($rowCount === 0)
{
echo 'Found nothing!';
}
else
{
echo "Found $rowCount rows!";
while ($row = mysql_fetch_array($q))
{
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
}
Check out mysql_num_rows
mysql_num_rows
$numberOfResults = mysql_num_rows($q);

Categories