convert php sql query while loop to for loop - php

In my code, 'product' table is returning every product details in the table.
Now I want to get specific product details of 0 to 5th product. How can I change this while loop to a for loop?
Code:
public function getProducts(){
$query = "SELECT * FROM shop_product";
$resultSet = Array();
$result = mysql_query($query) or die (mysql_error());
while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
$resultSet[] = $fetchResult;
}
mysql_free_result($result);
return $resultSet;
}

You could simply change your query instead to return top five rows.
SELECT * FROM shop_product LIMIT 0,5
(or)
If you don't prefer the above solution, you could use array_slice() to get a portion of the array..
while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
$resultSet[] = $fetchResult;
}
$fiverowsarray = array_slice($resultSet, 0 , 5); //<--- You can add like this..

Try with LIMIT and Where conditions
public function getProducts(){
$query = "SELECT * FROM shop_product LIMIT 0,5";
$resultSet = Array();
$result = mysql_query($query) or die (mysql_error());
while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
$resultSet[] = $fetchResult;
}
mysql_free_result($result);
return $resultSet;
}

Related

Get All Rows When Variable Empty PHP Mysql

$frame_type = '';
$ret = mysqli_query($con, "select * from products where status='1' AND frame_type = '$frame_type' ");
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
Get All Rows If The $frame_type Is Empty I am trying this way but i get zero rows , How to fix that Where $frame_type has value then send to query else not
There are a some of things that is wrong with your question (code). But if you only want answer. Just copy this
$frame_type = '';
$query = "select * from products where status='1' ";
// strlen has value
if(strlen($frame_type)) {
$query .= "AND frame_type = '$frame_type'";
}
$ret = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
PS: It's never a safe idea to pass everything to the query. Use prepared statement if you can.

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

How can I improve this PHP MySQL call?

I'm trying to update an older MySQL PHP method call but I end up calling the same SELECT call twice to achieve the same result. Is there a better way to do this?
Here is the original:
function updateProbabilities()
{
// first update the word count of each category
$rs = $this->con->select("SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id");
$total_words = 0;
while (!$rs->EOF()) {
$total_words += $rs->f('total');
$rs->moveNext();
}
$rs->moveStart();
if ($total_words == 0) {
$this->con->execute("UPDATE nb_categories SET word_count=0, probability=0 WHERE 1");
return true;
}
while (!$rs->EOF()) {
$proba = $rs->f('total')/$total_words;
$this->con->execute("UPDATE nb_categories SET word_count=".(int)$rs->f('total').",
probability=".$proba."
WHERE category_id = '".$rs->f('category_id')."'");
$rs->moveNext();
}
return true;
}
Here is my version:
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row['total'];
}
if ($total_words >= 1) {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$proba = $row['total']/$total_words;
$count = (int)$row['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}
Do you see any way I can avoid this second duplicate SELECT call?
The first time you run the query, add this to the while loop to store the results:
$rowarray[] = $row; // added to prevent running it twice
Then the second time it comes up, replace this:
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
with this:
foreach ($rowarray as $row) {
ALSO: move away from mysql_ functions, as they are deprecated and will soon be removed from PHP. Change to a PDO or MySQLi. You're already upating the code, may as well make that change too.
The mysql equivalent of $rs->moveStart() is:
mysql_data_seek($res, 0);
P.S. If you're rewriting into a new API, why are you using the deprecated mysql extension? You should use mysqli or PDO? They have similar methods for rewinding the cursor.
You can set the first query to a unique variable, and re-use the results of that query.
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
$results = array();
while ($row1 = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row1['total'];
$results[] = $row1;
}
if ($total_words >= 1) {
foreach ($results as $row2) {
$proba = $row2['total']/$total_words;
$count = (int)$row2['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row2['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}

how should i get ONE row from mysql? ( fetch_array etc? )

I'm pretty sure i'm doing an extra loop here:
$q = "SELECT * FROM genres WHERE genre.g_url = '$genre_url' LIMIT 1";
$res = mysql_query($q);
while ($r = mysql_fetch_array($res, MYSQL_ASSOC)){
foreach( array_keys($r) as $k ){
$g[$k] = $r[$k];
}
}
return $g;
$q = "SELECT
columns,
you,
want,
to,
read
FROM
genres
WHERE
genre.g_url = '".mysql_real_escape_string($genre_url)."'
LIMIT 1";
$result = mysql_query($q) or die(mysql_error());
return mysql_fetch_assoc($result);
If there is no row in the database this will return false, otherwise the data of the row. And don't forget to escape user inputs...

Checking if mysql_query returned anything or not

$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:
// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
// there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
// no data from query, react accordingly
}
You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}
If you loop through the results, you can have a counter and check that.
$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
$x++;
}
if($x == 1)
{
//No rows
}

Categories