php pdo loop through row skips 1st row - php

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>';
}
?>

Related

How to get specific column form mysql (PDO)?

I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}

PDO - Fetch Assoc in a 'while' loop

I'm trying to echo a bit of html within a while loop. I'm getting my stuff with PDO and PDO_ASSOC.
This is what I have:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book_id = $row['id'];
$book_title = $row['title'];
$book_image = $row['image'];
$book_amz = $row['amazon'];
$book_desc = $row['description'];
$book_rating = $row['rating'];
$book_date = $row['date'];
$book_author = $row['author'];
$book_categorie = $row['categorie'];
$text = "ID: ' . $book_id . '";
}
return $text;
But it gives me only one row of the table. I even tried fetchAll, but it gives me nothing.
So making the assumption that the only element ever seen is the last element it is because what your are returning is being overwritten each loop. There are a few options to resolve this. The simplest is:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$text = "";
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book_id = $row['id'];
$book_title = $row['title'];
$book_image = $row['image'];
$book_amz = $row['amazon'];
$book_desc = $row['description'];
$book_rating = $row['rating'];
$book_date = $row['date'];
$book_author = $row['author'];
$book_categorie = $row['categorie'];
//String concatenation of text will
//give you one big string at the end to return.
$text .= "ID: '{$book_id}'";
}
return $text;
However this will not work well with your real bootstrap html. You need to make sure that the columns add up right.
You will need something a bit more intuitive
Using the actual code it would look something like
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$bookEcho = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$bookEcho[] = '<div class="col-md-3">
<div class="thumbnail">
<span>' . $book_title . '</span>
<img src="' . $book_image . '">
<div class="book-options">
<span>Bewertung</span><br/>
' . $stars . '
Jetzt lesen
</div>
</div>
</div>';
}
return $bookEcho;
Now in your function what ever it is you can do something like (this is not the most elegant thing I have ever written but should get the job done):
$cols = 4;
$colCount = 1;
foreach ($bookEcho as $book){
if($colCount == 0){//create a row}
echo $book;
$coolCount++;
if($colCount == 0){end a row}
if($colCount == 4){ $colCount = 0;}
}
The problem is that you're overwriting your values in your while loop. The loop is being executed once for each entry in the database, but only the last one will be returned. Instead you want to use arrays:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$books = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book['id'] = $row['id'];
$book['title'] = $row['title'];
$book['image'] = $row['image'];
$book['amz'] = $row['amazon'];
$book['desc'] = $row['description'];
$book['rating'] = $row['rating'];
$book['date'] = $row['date'];
$book['author'] = $row['author'];
$book['categorie'] = $row['categorie'];
$book['text'] = "ID: ' . {$book['id']} . '"; // << Not sure if this is what you actually want. If not, adjust accordingly.
// Append the above values to the $books array
$books[] = $book;
}
return $books;
Use a foreach:
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($books as $book){
$book_id = $book['id'];
$book_title = $book['title'];
// ...
}

For each results- Mysql - JSON

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.

PHP And JS Code Not Executed

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.

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.

Categories