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.
Related
I am looping my rows from my database and it works except one thing. it skips the 1st id.
it begins from the second record. any idea how to fix this?
this is my code:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC)
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
<?php
// your first error is here. You are fetching the first row
$row = $query->fetch(PDO::FETCH_ASSOC)
// And here you start from the second, since you already did ones above
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//...rest of oyur code
}
?>
you have two way to accomplish your task
<?php
// Just add the PDO::FETCH_ASSOC constant while you are looping
while($row = $query->fetch(PDO::FETCH_ASSOC)){
//...Code here
}
// another way is adding the constant before using it
$query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
//...Code here
}
?>
Remove
$row = $query->fetch(PDO::FETCH_ASSOC) after $query->execute();
just keep the while($row = $query->fetch(PDO::FETCH_ASSOC)) statement.
Your code should be like this:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
Don't fetch twice for a query.
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
foreach ($query as $row) {
$id = $row['id']; $n = $row['name']; $cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
I want to pass multiple values through my url as below.
http://example.com/shopping_cart_json_api.php?uid=5710,55
I have created the php encode file as below however I am unable to get proper result out.
<?php
require('adminpanel/includes/application_top.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = explode(",", $_GET["uid"]);
$sth = mysql_query(" SELECT drug_medicines.fld_id,
drug_medicines.fld_image, drug_medicines.ld_product_name,
drug_medicines.fld_best_price,drug_cart.ld_userid,
drug_cart.fld_qunty, drug_cart.fld_totalprice
FROM drug_medicines
INNER JOIN drug_cart
ON drug_medicines.fld_id=drug_cart.fld_productid
WHERE fld_userid='" . $id . "' ||'" . $id . "'");
$rows = array();
while ($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
Format should be like this.
WHERE fld_userid='".$id[0]."' OR fld_userid= '".$id[1]."'");
For values more than 2 use
WHERE fld_userid IN (" . implode(',', $id) . ")"
As per your URL you might have more values in future so you should use IN function of mysql
fld_userid IN ($id);
Use IN in mysql query.
<?php
require('adminpanel/includes/application_top.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = explode(",", $_GET["uid"]);
$sth = mysql_query("
SELECT
drug_medicines.fld_id,
drug_medicines.fld_image, drug_medicines.ld_product_name,
drug_medicines.fld_best_price,drug_cart.ld_userid,
drug_cart.fld_qunty, drug_cart.fld_totalprice
FROM
drug_medicines
INNER JOIN
drug_cart
ON
drug_medicines.fld_id=drug_cart.fld_productid
WHERE
fld_userid IN (" . $_GET["uid"] . ")");
$rows = array();
while ($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
?>
You should use IN for more flexibility.
"... WHERE fld_userid IN (" . implode(',', $id) . ")"
Which will output:
"... WHERE fld_userid IN (5710,55)"
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.
i Have This PHP and JS Code on my web page.
<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
echo "<script type='text/javascript'>";
echo "this.styleListArray = new Array();";
if ($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
$counter += 1;
}
}
echo("</script>");
?>
The Problem is that when i execute the page containing the code, a part of this code doesn't get executed and it just shows on the page as a simple text :
"); echo "this.styleListArray = new Array();"; if ($result) { while($row = mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?>
I tried to figure it out, but i couldn't get it, if you can help brothers, that would be wonderful.
Try rewriting your code like this:
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array
echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;
$strLine = '';
if ($result) {
while($row = mysql_fetch_array($result)) {
$strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';";
$counter += 1;
}
}
echo $strLine;
echo("</script>");
First of all change your queries to use mysqli or pdo connections
secondly try following code
$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
$rows[] = $row['URL'];
$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';
echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';
check you console log.
You have $result = mysql_query($query) or die (mysql_error());; change it to
$result = mysql_query($query) or die (mysql_error());
Also make sure $row['URL'] and $row['user_fname'] are available.
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.