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

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.

Related

How to use mySQL data in PHP for loop?

I'm trying to get the last ID from mySQL script and then use it in PHP for loop to display each product that way so I don't need to type separately each one of them, maybe it's not the best solution, but this is prototyping. The problem is that nothing shows on the page when it's run, if there is a number instead of $last_id then it works
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$connection = new mysqli($serverName, $username, $password);
if($connection -> connect_error)
{
die("Connection failed: " . $connection -> connect_error);
}
$last_id = "SELECT id FROM tab_mobiteli ORDER BY id DESC LIMIT 1";
for($i = 0; $i < $last_id; $i++) {
echo "<p>This is text</p>";
}
?>
How can you be sure that you'll have ID's in perfect order. There could be a number in there that does not exist, since you can later delete some rows in the database. Anyway I usualy use PDO instead of mysqli but here's the idea. Just read everything and then you can play with the output in foreach loop.
$stmt = $connection->query("SELECT * FROM tab_mobiteli");
foreach ($stmt as $row) {
// here you do what you want to do for each db entry
// for example "echo $row['id'];"
}
You aren't executing the query this is why it will display nothing.
Here is an example of a query to a mysql db using PDO, read more about here.
<?php
$dbh = new PDO('mysql:dbname=test;host=localhost','root','root');
$stmt = $dbh->prepare("SELECT id FROM tab_mobiteli ORDER BY id DESC LIMIT 1");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0){
for($i = 0; $i < count($results); $i++) {
echo "<p>$results[$i]['id']</p>";
}
}
?>

How to display count of submitted radio button values using PHP [duplicate]

This question already has answers here:
Combine group by and count mysql
(2 answers)
Closed 5 years ago.
I am trying to display the total number of submitted radio button value, in my previous form, there is a choice between "Male", "Female" for user to choose and submit, and I have a database to store the values (radiob).
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
I have my code above only display all the items in the database under radiob,
Male
Male
Female
Is there anyway that I can display it with the total count?
Would want it to look like:
Male: 2
Female: 1
Use an Aggragage query with count
"SELECT count(id) as total, radiob FROM playertest GROUP BY radiob ";
I suggest adding an Auto Increment ID field as the primary key if you don't already have it.
This is known as a surrogate key in the Database world, and as your table grows you will really want to have one so you can properly refer to a row in other queries.
if you don't like that you can do
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$rows[] = $row["radiob"];
}
}
$totals = array_count_values($rows);
array_count_values() returns an array using the values of array as keys and their frequency in array as values.
http://php.net/manual/en/function.array-count-values.php
SO $rows should be like this
['male','male', 'female']
And array_count_values will give you this
['male' => 2, 'female' => 1]
Now if you want rows to contain more data such as
while($row = $result->fetch_assoc()) {
$rows[] = $row; //assume row is ['name'=>'foo', 'radiob' => 'male']
}
You can first do array_column such as ( to unwrap it )
$totals = array_count_values(array_column($rows, 'radiob'));
array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
http://php.net/manual/en/function.array-column.php
In summery the best way is to Aggregate it using the query, but you may have other data besides this you need ( such as name ), in that case do the second method.
Cheers!
Here is a possible solution. There are various ways to do it and I am not 100% certain of the output you want. But this might get you started. I added variables to hold the integer values of the male/female counts. I put them in an array with a key value that matches the values in your database. Then in each loop, the value is incremented on the total of the array element matching the DB row value. At the end I echo the two totals.
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
$array[ 'Male' => 0, 'Female' => 0 ];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$array[$row["radiob"]]++;
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
echo "Male {$array['Male']}\n";
echo "Female {$array['Female']}\n";
You should modify the code using a group by sentence to look like this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob,COUNT(*) as total FROM `playertest` group by radiob";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . ": ".$row["total"]."<br>";
}
} else {
echo "0 results";}
$conn->close();
?>

mysql fetch array individual echo 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

How to display data from a particular column across all row and loop it on a <p> tag?

I want to display data from all rows only for the column named 'text_notes' from my db.
And I want to loop that data in a p tag so that all data from column text_notes is displayed one by one till the end.
Below is the code I tried but it displays all the columns of the latest row and doesn't display the other rows.
I want the data from column 'text_notes' from all the rows to be displayed from latest at the bottom to the oldest at the top.
<?php
$query = "SELECT * FROM notes";
$conn = new mysqli(DBROOT,DBUSER,DBPASS);
$conn->select_db(DBNAME);
if ($conn == TRUE) {
$runQuery = $conn->query($query);
$resultNum = $runQuery->num_rows;
$result = $runQuery->fetch_array();
$resultRow = mysqli_fetch_row($runQuery);
$notes = $result['text_notes'];
for ($i = 0; $i < $resultNum;) {
echo "<p>".$resultRow[$i]."</p>";
$i++;
}
}
?>
$mysqli = new mysqli(DBROOT, DBUSER, DBPASS, DBNAME);
$query = "SELECT text_notes FROM notes";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Cycle through the result set
$counter = 0;
while(list($text_notes) = $result->fetch_row())
echo "<p>";
$counter++;
echo $counter . " : ";
echo " $text_notes </p>";
// Free the result set
$result->free();
I think it works :) Thanks

How to store all rows of a column name returned as a MySQL query result in a string array

I want to store all rows of a column name returned as a MySQL query result in a string array. I am new to PHP. I have retrieved the rows but how do I store all rows of a column in an array?
I mean how to iterate the counter of rows and store the column in an array? Or is there any direct function/method call? Please see my code below and its possible ways of storing in an array:
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'users';
mysql_select_db($dbname);
$result = mysql_query("SELECT users.email FROM users");
// AND THEN FINALLY STORING IN A STRING ARRAY:
$array = $result;
// OR SOMETHING LIKE:
Store($array, $result);
// OR SOMETHING LIKE:
for(int i = 0; i < $result.Rows.Count; i++)
{
if (null != $row[0])
{
$array[i] = $result[i];
}
}
// OR SOMETHING LIKE:
while($null != result.read())
{
$array.Add($result.Read());
}
MySQL Fetch Array
$result = mysql_query("SELECT users.email FROM users");
while($row = mysql_fetch_array($result)){
$array[] = $row;
}
This will return an array of associated arrays. The $row will contain the index of the column name along with integer index.
For example:
echo $row['email'];
//or
echo $row[0];
In the end you can get the first row by:
$array[0]['email']; //or $array[0][0];
NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead.
This is how you can do it
$rec = mysqli_query("SELECT users.email FROM users");
$data = array();
$i=0;
while($row = mysql_fetch_assoc($rec)){
$data[$i]['column1'] = $row['column1_from_table'];
$data[$i]['column2'] = $row['column2_from_table'];
$data[$i]['column3'] = $row['column3_from_table'];
}

Categories