I need to create loop, get lowest ID value from mysql.
So I tried this script:
<?php
include "configuration.php"; // mysql konfiguration
$jungiam = mysql_connect("$db_host", "$db_user", "$db_pass");
mysql_select_db($db_name, $jungiam);
$darom = mysql_query("SELECT * from task where id = (
SELECT
MIN(id)
FROM
task)");
$rez = mysql_num_rows($darom);
while ($rez > 1) {
$row = mysql_fetch_array($darom);
echo $komanda = $row['komanda'];
mysql_query('DELETE * FROM task WHERE komanda = ' .$row['komanda'].'');
}
return true;
?>
I need to get lowest id and print to page $row['komanda'], after printing delete from that table where komanda = $row['komanda'] (printed text).
After deleting record, I need to do script from the start, so it will print text with lowest id from mysql and after that text will be deleted and proccess will start from start and will be repeating until all records in table 'task' will be deleted.
"SELECT * from task ORDER BY id ASC LIMIT 1;"
This will return the first element with the lowest ID.
Related
I've tried to echo number of rows where a certain id=$id. This is essentially to count the number of "votes" a person has been receiving on the website. It works like a charm in mysqlworkbench, however the number of rows where this person's id has been inserted into database (through the voting button) won't show up on the webpage. The table name is forslag_stemmer, and it has its primary key= id, and foreign keys brukerid (the user that votes for a certain person) and foreign key forslagid (this is the people who receives votes from the users).
This query works in workbench, but not on the page:
echo "<u><b>Number of votes</u></b>:";
$sql= "SELECT COUNT( * ) FROM
bb.forslag_stemmer WHERE forslagid=$forslagid";
$resultat = $kobling->query($sql);
while($rad=$resultat->fetch_assoc())
{
$forslagid = $rad["forslagid"];
echo $sql;
echo "$resultat->num_rows";
}
I really don't know what to do?
You select one field COUNT( * ) as result of your query. There will be no other fields in a result.
echo "<u><b>Number of votes</u></b>:";
// I added an alias for field
$sql= "SELECT COUNT( * ) as votes_count FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$resultat = $kobling->query($sql);
$rad = $resultat->fetch_assoc();
// access value by alias
echo $rad['votes_count'];
mysqli_result::num_rows Gets the number of rows in a result
In your Example since you're querying as "select count(*) from table" it always returns Number of rows as "1"
You can get Number of rows in two ways
Method 1:
$sql= "SELECT * from FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$result = $con->query($sql);
echo $result->num_rows; // prints number of rows found
Method 2:
$sql= "SELECT count(*) as resultcount from FROM bb.forslag_stemmer WHERE
forslagid=$forslagid";
$result = $con->query($sql);
while($row = $result->fetch_assoc()){
echo $row['resultcount']; // prints number of rows found
}
I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>
I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>
I know there are libraries etc that I could use to get this sorted but Im almost there with my code.
A little about the code and what it's trying to do. I have a mysql table where there are various news articles and grouped in categories of news.
I have managed to get a forward button working. So it looks for the next news article that is in the same category. This works and the code is below.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id > '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"right\"><img title=\"Next News\" src=\"webImg/forwardarrow.png\"/></td></tr>";
}else{
echo "<td width=\"20%\"align=\"right\"></td></tr>";
}
//End of the next button
However, when I try do the same for the previous button. All I ever seem to get back is the first id of that category regardless of where my iteration is. For example, if I am on news article 10 and try to go to previous one which say has an id of 7 it will automatically show the first news article within that category, say id 4.
Below is the code.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id < '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"left\"><img title=\"Previous News\" src=\"webImg/backarrow.png\"/></td>";
}else{
echo "<td width=\"20%\"align=\"left\"></td>";
}
//End of the next button
What have I done wrong?
Thanks
Neither of your queries is correct. Your "Next" code selects any row whose ID is higher than the current, not necessarily the next one; if you get the next one, it's just by accident.
You should use ORDER BY and LIMIT to control which row is selected:
Next:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id > '$currentid'
ORDER BY id
LIMIT 1
Previous:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id < '$currentid'
ORDER BY id DESC
LIMIT 1
Without any further information, I don't think you can assume that the first row of your queries will be the ID you're looking for. Ordering by ID first will probably solve your problem; you can also limit your query to one row, since it's the only one you're looking at. Something like the following would probably solve your problem (where x is $storytype2 and y is $currentid:
SELECT * FROM news
WHERE storytype2 = x
AND id < y
ORDER BY id DESC /* <-- THIS */
LIMIT 1
Use ORDER BY id ASC for the other case.
Note that the MySQL family of PHP is deprecated and support thereof will disappear, if it hasn't yet. Please look into PDO or MySQLi.
Note also that you are inserting a variable into SQL code directly, which is never a good idea. I hope you have some good input checks on your variables.
Let's look at the PDO way to get the previous article ID:
$dbh = new PDO(..);
// Use ? where dynamic input will come
$sql = $dbh->prepare('SELECT * FROM news
WHERE storytype2 = ?
AND id < ?
ORDER BY id DESC
LIMIT 1');
// Fill the ? safely with PDO's execute function
$sql->execute(array($storytype2, $currentid));
$result = $sql->fetch(PDO::FETCH_ASSOC);
if($result && isset($result['id'])) {
// Process previous ID
}
Is it possible to limit the results shown from a MYSQL database?
At the moment the results are shown in a html table, how do I only show the newest entries?
<?php
$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cl49-XXX", $con)or die("Unable to select database");
$result=mysql_query("SELECT * FROM products") or die('You need enter a category');
echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
$catagory = $row['catagory'];
echo "
<td>$prodID</td>
<td>$prodname</td>
<td>$catagory</td>
<td>
<a href=deleteproduct.php?q=$prodID' class='btn mini red'>
<i class='icon-trash'></i> Delete Item</a>
</td>";
echo "</tr><tr>"; // it's time no move to next row
}
echo "</tr>"; // last row ending
?>
Just switch your query to something like this!
$result=mysql_query("SELECT * FROM products LIMIT 0,10")or die('You need enter a catagory' );
LIMIT 0,10 will show the first 10 results from your DB.
You could even order it by a specific element in your DB.
$result=mysql_query("SELECT * FROM products ORDER BY objectName LIMIT 0,10")or die('You need enter a catagory' );
For further SQL basic help: http://www.sqlcommands.net/
Good luck!
Your question Consists of two parts.
First part: Is it possible to limit the results shown from a MYSQL database?
you can do that by using limitword inside the query.
Example:
mysql_query("SELECT * FROM products limit 1, 5");
The previous code say select all products and start from the product one and show me 5 products only.
Second part: how do I only show the newest entries ?
You can do that by, must first create column called date to your products table, then when add new product, store the time by using time() function into date column.
Then when you want to show the products order by newest products, you can use order by sentence.
Example:
mysql_query("SELECT * FROM products order by date ASC limit 1, 5");
To apply these words on your code, only need to
Add new column in your products table and call it date.
Then change the query that adds the products to products table to add also
the time to the date column by using time() function.
INSERT INTO tableName(date) VALUES('".time()."');
Show the products sorted order by newest by modify the query to
$result=mysql_query("SELECT * FROM products ORDER BY date ASC LIMIT 0, 15") or die('You need enter a category');
First of all, while you're still new, you should look into PDO/Prepared statements instead of mysql_ functions.
Also, you can do this for your SQL:
$result=mysql_query("SELECT * FROM products ORDER BY name DESC LIMIT 0,10")or die('You need enter a catagory ' );
'name' being the name of your products/row name you wish to sort it by
just add a counter and when the counter hits a number use:
break;
to jump out the loop.
for example
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
if ($i==3) break;
}
Of course you could better limit the loop itself:
use:
for ($i = 1; $i <= 4; $i++)
or use the LIMIT option in the SQL-query