This is my php code for displaying the data from the database. I am trying to display the random data from table.
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
But the problem with this code is:
It is displaying nothing. But whenever I am trying to make a little modification in the above code like:
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows && $i<4)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
$i=$i-1;
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
It is displaying the same single output 4 times. But It has to display the four different output. So, Please tell me where is the bug ... And how am i suppose to display four different random output.
Any help will be appreciated
Thanks in advance
Your first Query is fine, but the while is wrong:
Just look at what you did here:
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
this will end in an "infinite Loop" cause $rows will always be set.
What you need is:
while($rows=mysql_fetch_array($query_run))
this will cause myslq_fetch_array to return a new line everytime the while condition is checked. And if all 4 rows are returned, $rows will be false and the loop is stoped.
And to be complete:
In your second Example you are exactly iterating 4 times over the SAME row, you just fetched one time by calling myslq_fetch_array.
A possible solution to that will be to fetch the row again INSIDE the while-loop:
$i=4;
while ($i>0){
$rows = mysql_fetch_array(...);
$i--;
}
However you should prefer the first solution, because then you dont need to take care that the result count matches your iterator variable.
sidenode: Call it $row without the 's', because you always just getting ONE row back.
Try constructing while loop like so
while(($rows=mysql_fetch_array($query_run)) !== false)
Using ORDER BY RAND() is not the best practice because the random value must be generated for every single row. Better way would be to randomly generate primary keys (e.g. ID) in PHP and then select according to them.
$random_id = rand(1,4);
$query="SELECT * FROM `banner_ad` WHERE id = $random_id";
Will select exactly one random row. Similar whould be selecting multiple rows using IN statement.
More info you can find here.
$query_run=mysql_query($query);
if(!$query_run)
{
echo'<span style="color:red">Query did not run.</span>';//font tag is ancient
}
else
{
if(mysql_num_rows($query_run) > 0)
{
while($row = mysql_fetch_assoc($query_run))
{
echo $rows['banner_no'];
echo $rows['banner_name'];
// more...
}
}
}
Related
So I have been working on this code for a while. I believe I am really close. My if statement that is inside my while loop isn't showing any data in the area it's suppose to show. I know mysql is old and deprecated. I am going to change it once I figure this out.
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$result2 = mysql_query("SELECT * FROM users WHERE username='$username' and sub = 'yes'",$db);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD>"."<B>Title</B>"."</td>";
echo"<TD>"."<B>Authors First Name</B>"."</td>";
echo"<TD>"."<B>Authors Last Name</B>"."</td>";
echo"<TD>"."<B>ISBN</B>"."</td>";
echo"<TD>"."<B>Publisher</B>"."</td>";
echo"<TD>"."<B>Course Number</B>"."</td>";
echo"<TD>"."<B>Source</B>"."</td></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
?>
This is the part of my code that isn't showing any results.
while
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
I want my session user to be able to see the source from my inventory table if they have a yes in the sub field. If they do not have a yes in the sub field, they will see please subscribe to view. Am i doing the mysql_fetch incorrectly or is there a problem because I have 2 while loops going on at once.
you need to have "==" to compare two values, otherwise you assign the second value to the first variable:
...If($username == $subResults)...
or to use a strict comparison of type and content, use "==="
If($username === $subResults)
also I am thinking the code should be
...If($subResults ==="yes"){echo"....///desired content";}else{echo"...//alternate content";}...
and you are missing the echo statement and closing </td> in the code
"<td>".$myrow["source"];
should be
echo"<td>".$myrow["source"]."</td>";
in fact - aren't you missing the closing td's in all of the cells?
All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable
Here is my code:
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
$conn=mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name'],$conn);
$exec_query =mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
The Problem is that I am not getting anything in $row I cant get into the while loop, nothing shows up when I try to echo the value of $row, No error Nothing. Can you help me to find a problem in my code ?
Ps : The database is their. I have checked for the query for the corresponding value of $campagin_id. and also when i tried to echo $exec_query it echoed this : Resource id #8
PPS : The database have more than 7 record for each id so it doesn't matter if I call mysql_fetch_array($exec_query) more than once before going in to the while loop. and for the $campagin_id in the session their are many records present in the database.
You have written $row=mysql_fetch_array($exec_query) and then you are echoing something. and you are using the same in while.
Instead of:
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
Use this (as per my knowledge you should not use $row=mysql_fetch_array() once you have used before while):
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
If the query returns Resource id #8 then that means it was successful - ie there were no errors. There were probably no rows returned by that query, so no rows in your table that match the given campagin_id.
You are also calling mysql_fetch_array() twice separately, you shouldn't do that because your while loop will skip the first row because calling this moves the pointer in the result set forward by one.
Also you can't echo an array as you are trying to, if you want to see the contents of an array use print_r() or var_dump().
I suggest adding some code to handle no rows found:
if($exec_query && mysql_num_rows($exec_query) > 0)
{
while ($row=mysql_fetch_array($exec_query)){
echo "Row: " . print_r($row, true);
}
}
else
{
echo 'None found';
}
Try this code.
<?
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name']);
$exec_query =mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_assoc($exec_query)) {
echo "<br/> row = <pre>".print_r($row)."</pre><br/>";
}
?>
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)
I am designing an event feed from a calender I made. I'm using the same data from the database but to match specific dates and times.
I only want 4 events to show at once (why I specified length < 4)
Where the database value 'showFeed' is true, it only displays those rows.
and I want it to show by date time, I have odd id's for each value in the database, which might make them out of order.
My current code:
$sql = "SELECT `title`, `time`, `start`, `showFeed` FROM calender WHERE length('column') > '0'";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo "<div class=\"eventfeed\">";
echo "<ul>";
foreach ($result as $row){
$show = $row['showFeed'];
if ($show == 1 && length.$result < 4){
echo "<li>";
echo $row['title']. "<br />";
echo $row['start'].' '.$row['time'];
echo "</li>";
}
else {
return false;
}
}
echo "</ul>";
echo "</div>";
$dbh = null;
echo json_encode($return);
?>
I'm getting results and no errors from the database, but I'm only seeing one return on $results.
I honestly, do not have a clue where else to go from here. I'm lost.
For 1+.2.+3. modify your query to SELECT title, time, start, showFeed FROM calender WHERE length('column') > '0' and showFeed=1 and time<current_timestamp ORDER BY time DESC LIMIT 0,3 and remove your if (...) statement.
I don't know if this is your actual code, but you should determine the length of an array by doing $result.length instead of the other way around.
Also, you can limit the number of results in your query using 'LIMIT 4' at the end of your query. That way MySQL only returns 4 results and you don't have to worry about that in your code, just print everything.