I have this bit of code that doesn't produce anything, not even an error message. I'm trying to echo the result inside the while loop, but even that doesn't show anything. Any tips?
foreach($droppedStudentIds as $value){
$query3 = "select * from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists)";
if($result = mysqli_query($mysqli, $query3)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "Date: ".$row['ClassListDate'];
$droppedStudentIds[$value][] = $row['ClassListDate'];
}
mysqli_free_result($result);
} else die ("Could not execute query 3");
}
My goal is to look up a date information for each element inside the $droppedStudentIds array. I checked the MySQL query in itself and it produces that desired result.
Thanks!
You're assigning to the array you're looping through on this line:
$droppedStudentIds[$value][] = $row['ClassListDate'];
This could be causing your script to timeout, which would be why you're not seeing any output.
I'd add a second array to avoid conflicts and use that for storing results from the query, e.g.
$temp[$value] = $row['ClassListDate'];
Thanks all for the response, it helped pin down the mistake!
No need for a while loop when asking for a single record
The query was actually incorrect. The subselect was getting the maximum date in the database, regardless of whether the StudentId was present or not. The correct query is the following:
select ClassListDate from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists where StudentId = '$value')
Thanks again!
Related
the first, my current code is
$sql = "SELECT COUNT(id) AS total FROM mytable WHERE something = ".$likethis;
$query = mysqli_query($connection, $sql);
$result = mysqli_fetch_object($query);
if the result give 1 or more data, then i do this query to get the data
$sql = "SELECT col1, col2, col3 FROM mytable WHERE something = ".$likethis;
the second one, another method i found is using this code
$totalRow = mysqli_num_rows($query);
then if give 1 or more, i do fetch the data.
in my head now is, the first one is fast on counting data then only do the rest if have result. but need connect to database twice.
the second one is slower because need to read all data but only connect to database once.
i'm not sure my opinion is accurate it just by how much php read database, and not sure actually which one is better.
or maybe there are other better way to do:
- check how much row it have
- get the rows if have
You can set flag for check you can get row/rows or not. If you can't get any row from database flag is true.
For e.g.
$query = mysqli_query($connection,"select * from `test`");
$flag = true;
while($rows = mysqli_fetch_array($query)){
$flag = false;
// Do stuff.
}
if($flag){
echo "No record found.";
}
If can not get results code will print else part.
I am trying to display posts in a specific condition with a while loop but it is giving me a 30 second timeout error. Here's my code:
while ($tagrow = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC"))) {
$stufftoecho .= $tagrow['text'];
}
There is a timeout error on the line with the while loop, I guess it is an infinite loop but I don't know how to fix it.
NOTE: Please don't tell me I need to use mysqli or PDO, i will convert to one of them later.
Run mysql_query() once out of while loop.
$sql = "SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['text']; }
mysql_free_result($result);
This of course is going to be an infinite loop, provided at least one element matches the query; I suspect that in your infinite loop, you never progress past the first element returned by the query.
while ($tagrow = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC"))) {
The function mysql_fetch_assoc is going to take in a result set of a query, and iterate through it, returning the next element in the series each time it is called.
The function mysql_query is going to take a query and return a result set;
They way you have your while loop structured, you will be executing the query, and passing the result set directly into the fetch_assoc, which will inturn assign the value of $tagrow to the first element; and then do it again, and again.
What we need to do instead, is execute the query, and then save the result set. This makes it so you only need to execute the query once, instead of on each iteration, and save the results in memory.
We can do this by simply breaking it into the following two lines, and using a variable as temporary storage of the query results.
$results = mysql_query( "SELECT * FROM posts WHERE tag='$usersearch' ORDER BY id DESC" );
while ( $tagrow = mysql_fetch_assoc( $results ) ) {
I'd suggest you to break it up into chunks.
$query = mysql_query("SELECT * FROM posts WHERE tag='".$usersearch."' ORDER BY id DESC") or die(mysql_error());
while ($tagrow = mysql_fetch_assoc($query)) {
$stufftoecho .= $tagrow['text'];
}
Hope this helps.
Peace! xD
It seems your running the query every time it goes through the loop. Try this instead,
$result = mysql_query("SELECT * FROM posts WHERE tag='" . $usersearch . "' ORDER BY id DESC"); //execute query
if ($result)
{
while ($tagrow = mysql_fetch_assoc($result))
{
$stufftoecho.= $tagrow['text'];
}
}
else
{
echo mysql_error();
}
How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];