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/>";
}
?>
Related
Simple Login Form Using PDO .The Output of echos works fine .Enters inside the else case But does not go inside the foreach loop.
The output of var_dump gives this .
echo output
1rows SelectedEntered successfull loop
var_dump output
object(PDOStatement)[3] public 'queryString' => string 'select *
from tour_login where username='admin' and password='admin' and
status=1' (length=81)
if(isset($_POST['login']))
{
$un=$_POST['un'];
$pass=$_POST['pass'];
$res=DB::getInstance()->query("select * from tour_login where username='$un' and password='$pass' and status=1");
$num_rows = $res->fetchColumn();
echo $num_rows."rows Selected";
if($num_rows<=0)
{ echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
else
{
echo "Entered successfull loop";
foreach ($res as $row) {
echo "Entered successfull for loop";
if($row['type']==0)
{
$_SESSION['admn']=$un;
echo "<script>alert('welcome admin...');document.location='adminhome.php';</script>";
}
else
{
$_SESSION['usr']=$un;
echo "<script>alert('welcome user...');document.location='userhome.php';</script>";
}
}
}
}
What I am not understanding is why foreach is not working with number of rows showing one.New to Php.I found alternative of using mysql_num_rows() in pdo in this StackOVerflow Question
https://stackoverflow.com/questions/11305230/alternative-for-mysql-num-rows-using-pdo
Your first problem is that, being a novice, you just snatched one line from the code you found, having no idea what does it do. This line would never return number of rows found, yet this line is responsible for your confusion, as it fetches all the data you selected, leaving nothing for the foreach loop. Though you don't need the latter as well.
Your second problem is that you are under a very common delusion, thinking you need number of returned rows at all. In fact, you don't actually need it.
Your third problem is that you ought to be using prepared statements but you aren't.
The code you need is
$sql = "select * from tour_login where username=? and password=? and status=1";
$res = DB::getInstance()->query($sql);
$res->execute(array($un, $pass));
$row = $res->fetch();
if(!$row) {
echo "Entered error loop";
echo "<script>alert('invalid username and password');document.location='index.php';</script>";
return false;
}
and so on. Just remove useless foreach loop and you're set.
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 1 year ago.
I am updating a mysql table. i am getting an error as below
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\test\edit.php on line 232
Error. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
The query seems not to be producing a result. I am passing an id to a function via a url but the variable seems to die although it seems to be in scope. What could be my error. The loop for the update is below. i have commented out some lines which i thought where a problem but they are fine. code in bold are the problem lines.
elseif(isset($_POST['editSelection']))
{
// check if form is submitted
//collect variables posted by form.
$fixture_id = mysql_real_escape_string($_POST['fixture_id']);
$goalkeeper = mysql_real_escape_string($_POST['goalkeeper']);
$defender = mysql_real_escape_string($_POST['defender']);
$fullback = mysql_real_escape_string($_POST['fullback']);
$midfielder = mysql_real_escape_string($_POST['midfielder']);
$wing = mysql_real_escape_string($_POST['wing']);
$striker = mysql_real_escape_string($_POST['striker']);
$sid = mysql_real_escape_string($_POST['sid']); // receive the selection_id which was posted from the hidden field in the editForm
$sql = "SELECT * FROM `selections` WHERE selection_id = {$sid}";
$data = mysql_query($sql);
**while($rows = mysql_fetch_array($data))
{
$opponents = $rows['opponents'];
}**
//validate form by checking for empty strings that user might have submitted using strlen() php built-in method. If no empty string form processes
//if(strlen($fixture_id)>0 && strlen($goalkeeper)>0 && strlen($defender)>0 && strlen($fullback)>0 && strlen($midfielder)>0 && strlen($wing)>0 && strlen($striker)>0 && strlen($selection_id)>0) { // if form fields are not empty, update Selection record in database
$sql = "UPDATE `selections` SET goalkeeper ='{$goalkeeper}' WHERE selection_id = {$sid}";
$query = mysql_query($sql) or die("Error executing query ".mysql_error());
echo "Selection updated <br/><br/>";
echo "Go back to Team Selections page ";
//}
}
echo"<tr><td>Midfielder</td><td><select name=\"midfielder\">";
$sql = "SELECT name FROM `player` ";
$data = mysql_query($sql);
while($rows = mysql_fetch_array($data)){
echo "<option value={$rows['name']}>";
echo $rows['name'];
echo "</option>";
}
echo "</select>";
echo "</td></tr>";
echo"<tr><td>Wing</td><td><select name=\"wing\">";
$sql = "SELECT name FROM `player` ";
$data = mysql_query($sql);
while($rows = mysql_fetch_array($data)){
echo "<option value={$rows['name']}>";
echo $rows['name'];
echo "</option>";
}
echo "</select>";
echo "</td></tr>";
echo"<tr><td>Striker</td><td><select name=\"striker\">";
$sql = "SELECT name FROM `player` ";
$data = mysql_query($sql);
while($rows = mysql_fetch_array($data)){
echo "<option value={$rows['name']}>";
echo $rows['name'];
echo "</option>";
}
echo "</select>";
echo "</td></tr>";
echo "<tr><td></td><td><input type=\"hidden\" value=\"{$rows['selection_id']}\" name=\"sid\"></td></tr>"; // create hidden field with selection_id which enables the right selection to be edited
echo "<tr><td></td><td><input type=\"submit\" value=\"Update Selection\" name=\"editSelection\"></td></tr>";
echo "</table></form>";
} //end of while loop
}
mysql_query() returns a result set if it works, or false if it doesn't work. The fact that you're getting complaints from mysql_fetch_array() about using a boolean where a result set is required means that the query has returned false (ie, it hasn't worked).
Yous should use something like:
$data = mysql_query($sql) or die (mysql_error());
to see what the actual error is though I'd be looking at something a little more robust in production code. Still, that should be enough to identify the immediate problem.
You may also want to actually output the query before trying to execute it in case, for example, there's a problem with $sid, such as it being empty, or it being a string where your query seems to desire a numeric value.
If it is a string, you'll want to surround {$sid} with single quote marks:
$sql = "SELECT * FROM selections WHERE selection_id = '{$sid}'";
If it's empty, you'll need to track down why, since that will give you the invalid query:
SELECT * FROM selections WHERE selection_id =
And, of course, you should be moving to the mysqli_* functions where possible since the mysql_* ones are deprecated.
Have you tried adding mysql_error() to see what error message you are getting?
Change this:
$data = mysql_query($sql);
to this:
$data = mysql_query($sql) or die(mysql_error());
The message you are receiving is saying that the result of that query is a true/false, not a mysql "resource". MySQL resources are the normal response of a mysql query, and they can be "read" by using mysql_fetch_array or mysql_fetch_assoc, etc.
So if you are getting a true/false response, then that particular query isnt giving you the data you desire. Troubleshoot with me: why is that happening?
Try this:
"SELECT * FROM `selections` WHERE `selection_id` = '$sid'";
Also, echo out the value of $sid so you can see that it has something in it. A null return will also not work in mysql_fetch_array.
Also try echoing out the entire $_POST to see exactly what is being received:
echo '<pre>';
print_r($_POST);
echo '</pre>';
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...
}
}
}
I wrote the following code to select text from database,but when i echo the output it giving output as Resource id #4
mysql_select_db("xxxxx", $link);
$q = "SELECT start_of FROM `qr_table` WHERE id_qr =1";
$result = mysql_query ($q, $link);
echo $result;
i am new to sql,forgive me if its a stupid questain
Thanks in advance
I suggest you to read at least Php documentation about Mysql query function.
you are echoing out the connection. you need to do something with the results like loop through them please check http://www.php.net/manual/en/function.mysql-query.php
You can't print out the result from MySQL directly. Try mysql_fetch_assoc(), which loads the value of each column into an associative array. if you have multiple rows returned, it will move to the next one each time it is called, and return false when there are no more.
this help for you
<?php
$link=mysql_pconnect("localhost","root","")or die("Not connected".mysql_error());
mysql_select_db("test");
$query="select * from qr_table";
$result=mysql_query($query,$link)or die("Query failed".mysql_error());
print "<center><table border=1>\n";
while($line=mysql_fetch_array($result,MYSQL_ASSOC)){
print "\t<tr>\n";
foreach($line as $col_value){
print "\t\t<td>$col_value</td>\n";
}
print "\t</tr>\n";
}
print "</table>\n</center>";
?>
Bit confused with this one.
Basically, I have a column in a table, and I want to retrieve the value in that column, for a specific row.
I have one set of code that works, but not in this particular situation.
The code I have that works is this:
$qry="SELECT * FROM logins WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);
This obviously retrieves that particular row, and then:
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['User ID'];
This successfully sets the session variable, as the value from the user id column from this row.
So that's fine, that works. The code I am trying to use in my new situation is this:
$qry = "SELECT * FROM vote WHERE Username = '" .$_SESSION['SESS_USERNAME']. "'";
$result = mysql_query($qry);
This gets the row based on the current user, and then:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The while loop works correctly, it displays the current username, and their vote. Obviously I felt the loop was not required as I already have just the one row selected. Removing the loop broke it, so I put it back. Not a big deal, I can live with that if it gets the job done.
The issue I am focusing on, is the use of the
$row['Username']
In this if statement:
if($row['Username'] == "Admin") {
echo ("Win!<br />");
}
else {
echo "Failed!";
}
When printing from the loop above, it prints:
Name, as Admin,
and vote, as 0.
If I then try to validate using the if statement, I ask it to echo Win! if the username == Admin.
Obviously it is true as it has printed it on the line before, however, it always prins Fail! and I can't understand why.
Should I set $row['Username'] as some other variable?
Can anyone offer their guidance please?
Cheers
Eds
The problem stems from your loop:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The first time through, $row is set to the row of data from the database. It then tries to go through the loop again, but since there is only one row, mysql_fetch_array returns false. now $row is set to false. So any code after the loop won't have access to the data anymore.
The solution would be to replace your loop with a simple if statement:
if ($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
I fail to see how your PHP code could produce that "it prints" sample. However, check that your Username field actually contains an exact "Admin" string. It may have a linebreak or other whitespace in it. Doing a
var_dump($row['Username']);
should show something like
string(5) Admin
The bracketed number (5) is the length of the string. If it's not 5, then you've got some extra stuff in the string causing the == 'Admin' test to fail.