mysql fetch array individual echo php - php

need to get row content from a mysql select statement. Currently starting at high id and desc. Need to take the highest id and get it, and the next 15 in line, and need to store them as variables. Here is an example:
$servername = "localhost";
$username = "_p";
$password = "1";
$dbname = "w";
mysql_connect("localhost", "p", "s") or die(mysql_error());
mysql_select_db("p") or die(mysql_error());
$highest_id = mysql_result(mysql_query("SELECT MAX(id) FROM NE2"), 0);
$result = mysql_query("SELECT content, id FROM NE2 order by ID desc LIMIT 15 ");
while($row[0] = mysql_fetch_array($result)){
echo $row[0]['content'];

You could do it with one query and access the top 16 ids, (the max id and the 15 next ids)
$servername = "localhost";
$username = "_p";
$password = "1s";
$dbname = "wc";
mysql_connect($servername, $username, $dbname) or die(mysql_error());
mysql_select_db("we_ppp") or die(mysql_error());
// Let's get the 16 first highest id's and their content
// Why 16 ? We want the highest and the 15 next
$result = mysql_query("SELECT content, id FROM SEARCH2 order by ID desc LIMIT 0, 16");
// Now it's easied to handle if we just stack the result in a big array
$data_array = array();
while($row = mysql_fetch_array($result)) {
$data_array[] = $row;
}
// Now we have $data_array[0] to $data_array[15] (the 16th row) each one containing
// an associative array resulting from the mysql_fetch_assoc().
// Now if I want the highest id :
$highest_id = $data_array[0]['id'];
$highest_content = $data_array[0]['content'];
// And the next 15 are
for($i = 1; $i < 16; $i++) { // We start at the second line until the 16th (numer 15)
echo $highest[$i]['id'];
echo $highest[$i]['content'];
}
// Now you do whatever you want with $highest and the next ones
The code will be more readable here :
http://pastebin.com/jGF94WJ2

use it like this
$result = mysql_query("SELECT content, id FROM S_ENGINE2 order by ID desc LIMIT 15");
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo $row['content']."<br>";
}
}
may this will help you

The while loop executes row by row, and at an instance you could have only one row (just like array index), so do like
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["id"];
echo $row["contetnt"]);
}
NOTE: mysql_* is deprecated and is not advised . Use PDO for secure database interations

Related

My for loop only allows one post to be displayed, over and over again

/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html

Mysql query don't get first row in PHP [duplicate]

This question already has answers here:
mysqli ignoring the first row in a table
(4 answers)
Closed 1 year ago.
I trying to get the latest orders in my database and show in php frontend.
The problem is when i print the data, the first element in the array is not appear.
Example code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDatabase";
$db = new mysqli($servername, $username, $password, $dbname);
$counter = 0;
$query = "SELECT * FROM `orders` WHERE `supplier` = '".session('email')."' ORDER BY `id_order` DESC";
if ($result = $db->query($query)){
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
$name = $row["name"];
$orderID = $row["id_order"];
$ordersArray[] = array('id_order'=> $orderID,
'name'=> $name, );
}
foreach($ordersArray as $row){
if( $counter <= 4 ){
echo ($row["name"]);
echo ($row["id_order"]);
$counter = $counter + 1;
}
}
} else {
echo ('<tr><td>No tienes ordenes recientes</td></tr>');
}
}
$db->close();
Example output
4
3
2
1
I have a fifth value in the database that should be displayed first, but it does not appear
You fetch the first row already before the while loop starts...
$row = $result->fetch_assoc(); // << first row feteched here
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
Remove the random fetch:
$row = $result->fetch_assoc();
Making this call moves the result pointer up but you're not adding this row to $ordersArray.
Alternatively, if for some reason you do need to access the first row outside your while loop, either add the data to the new array or use $result->data_seek(0) to reset the pointer.

Placing single column database values into an array then calling them in another query

I'm having trouble with pulling database information from 'rownum' column and putting it into an array and then using that array information for my next query that randomly selects one line of the array and then displays it.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
I'm not sure what I have done wrong? Does the array have to be echoed and then my $query line calls that instead?
Updated code - Solved my problem
Thanks for tips guys, it helped me wrap my head around it and came up with a working solution.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
//pick a random point in the array
$random = mt_rand(0,count($all_rownums)-1);
//store the random question
$question = $all_rownums[$random];
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
This part is what helped me solve it:
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
Happy Dance

get prior row from a mysqi query in php

I have a view in MySQL called published_people that looks like this:
PersonID Name LastName MarkerID date
-------- ---- -------- -------- ----
1198 Jane Doe Doe 1174 2015-05-20
864 John Doe Doe 863 2015-04-23
1187 Richard Roe Roe 1165 2015-05-21
1190 Sam Spade Spade 1167 2015-01-01
I have a post variable representing the marker ID of the person whose page of data I'm viewing.
I have another post variable that represents the last name of the person whose page of data I'm viewing.
I want to be able to iterate through published_people. If the LastName field matches the variable, I want to get the prior record (the one before this one) in published_people.
Here's my code in php so far:
include_once ('constants_test.php');
$mysqli_prior = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
//get the year I'm looking for
$this_date = mysqli_real_escape_string($mysqli_prior, $_POST['this_date']);
$pieces = explode("-", $this_date);
$this_year = $pieces[0];
//find the last name of the person I'm looking for
$marker_id = $_POST['marker_id'];
$q_getLastName = "select LastName from published_people where MarkerID =" . $marker_id;
$result = mysqli_query($mysqli_prior,$q_getLastName);
$r = $result->fetch_row();
$thisLastName = $r[0];
//get all records from this year, alphabetized by last name
$q = "select * from published_homicides where year(date) = '" . $this_year . "' order by LastName";
$result = $mysqli_prior->query($q);
$allresults = array();
$num_rows = mysqli_num_rows($result);
if ($num_rows != 0) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
// How do I say this?
// if $row["LastName"] == $thisLastName then find the record
// PRIOR TO this one and do the following:
$results = array($row['Name'], $row['date']);
array_push($allresults, $results);
}
echo json_encode($allresults);
} else {
echo "nothing";
}
mysqli_close($mysqli_prior);
I ended up creating a variable to hold the data from the previous record. I iterated through the query. When the MarkerID equaled the marker_id of the record I wanted the previous one of, I stopped:
$priorname = ""; //initialize at nothing
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
$results = array($priorname);
array_push($allresults, $results);
} else {
$priorname = $row['Name']; //save this data in $priorname
}
}
echo json_encode($allresults);
mysqli_close($mysqli_prior);
So that was getting the prior record.
I also wanted to get the next record.
I handled this problem in two parts. First I went through my query, counting the row I was on. When my post variable called marker_id matched the MarkerID in the database view, I stopped the query:
$marker_id = $_POST['marker_id'];
$q = "select MarkerID, Name, LastName, date from published_people order by year(date) desc, LastName asc";
$result = $mysqli_next->query($q);
$allresults = array();
$count = 0;
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_BOTH)) {
$count++; //keep track of what row you're on
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
//if they're the same, stop this query - we have counted to the spot that they matched
break;
}
}
Now I know where to set a limit on another query:
//make a new query with a limit of one record starting at the row # indicated by $count
$newq = "select MarkerID, Name, LastName, date from published_homicides order by year(date) desc, LastName asc LIMIT " . $count . ",1";
$result2 = $mysqli_next->query($newq);
while($row2 = $result2->fetch_array(MYSQLI_ASSOC)) {
$results = array($row2["Name"]);
array_push($allresults, $results);
}
echo json_encode($allresults);
mysqli_close($mysqli_next);

Get top 4 highest rows based on ID

I'm trying to grab the highest 4 rows in a table and assign variables to them so that I can use them throughout my code.
Here is what I was able to get so far...
<?php
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
$conn = mysqli_connect(localhost, $username, $password, $database);
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
$name =($row["name"]);
$message =($row["message"]);
$time =($row["time"]);
}
?>
How am I able to assign more variables to get the next 3 rows?
I believe it's (sorry, long day so I might be off)
$result = array();
while(...){
$result[] = $row;
}
I suggest you loop through the result set and assign each iteration to an array, you can then pull the values back out of the array later.
Here is a working update to your code
// ...
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
// create array to hold queried result set
$output = array();
// loop through result set and assign each row to a key in $output array
// Note: the fetch_assoc() method auto-increments an internal pointer
// so as you spin through the result set $row will move down the rows
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
// $output now contains an associative array on each key representing
// each row, so to access each row:
foreach($output as $row) {
echo $row["name"] . "<br>";
echo $row["message"] . "<br>";
echo $row["message"] . "<hr>";
}
Define $result as array after while
$result = array();
while($row= .... ){
$var= $row['name'];
.............
}

Categories