php mysql pdo resultset with one row not entering foreach - php

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.

Related

Display the result table for 2 sql queries in php

I'm writing a php file, and I want to show two tables by executing 2 seperate queries, and store them in $result and $result_bike. However, when I try to open the html page for this action form, it only shows the table for the first query, and gives the error " Commands out of sync; you can't run this command now" at the place of the second table.
Also, I don't want to combine these two tables, as they show entirely different information and I want to insert some text explaining each table.
I think there might have something to do with not able to print two tables for php (which I doubt)? What change should I make?
Thank you in advance for the help!
$result = mysql_query("CALL CrashTypeRate_Ped('$city')", $conn);
if (!$result){
echo "Fail to retrieve result for pedestrian crashes!\n";
print mysql_error();
} else {
echo "<table border=1>\n";
echo "<tr><td>CrashType</td><td>Count</td><td>TotalCount</td></tr>\n";
while ($myrow = mysql_fetch_array($result)) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n", $myrow["crash_type"], $myrow["type_count"], $myrow["total_count"]);
}
echo "</table>\n";
}
$result_bike = mysql_query("CALL CrashTypeRate_Bike('$city')", $conn);
if (!$result_bike) {
echo "Fail to retrieve result for bike crashes!\n";
print mysql_error();
} else {
echo "got here!!!!!!";
echo "<table border=1>\n";
echo "<tr><td>CrashType</td><td>Count</td><td>TotalCount</td></tr>\n";
while ($myrow = mysql_fetch_array($result_bike)) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n", $myrow["crash_type"], $myrow["type_count"], $myrow["total_count"]);
}
echo "</table>\n";
}
Here is from PHP Documentation user comments. Hope this helps
Link to PHP Documentation
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:
<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// 1st Query
$result = $db->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
// 2nd Query
$result = $db->query("call getGroups()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$group_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
else echo($db->error);
// Close connection
$db->close();
?>

Select from multiple MySQL tables

i'm trying to select value from different tables but i face some errors in the result i want to check if there is any values i will echo "Yes" otherwise echo "No"
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username=$_POST['username'];
require_once('dbConnect.php');
$sql="SELECT donator.national_id, needy_people.national_id".
"FROM donator, needy_people".
" WHERE donator.national_id='$username' OR needy_people.national_id='$username' limit 50";
$result=mysqli_query($con,$sql);
if($check>0){
while($row=mysql_fetch_array($sql)){
$check=mysqli_fetch_array(mysqli_query($con,$sql));
}
}
if(isset($check)){
echo'YES';
}else{
echo'Noooo';
}
mysqli_close($con);
}else{
echo'error';
}
can anybody solve this problem help!
When you put as condition if($check>0), $check is not defined yet, so it won't be processed, hence $check stay unset.
Also you should use the empty() function to test existence of values in it
If you're trying to check if a row exists when you run your query consider using the function mysqli_num_rows
if (mysqli_num_rows($result) > 0) {
echo "Has row";
}
$count=mysqli_num_rows($check);
if($count>0)
echo "yes";
else
echo "no";

Why is my else statment running the code twice

My code:
<?php
$name = $_POST["name"];
//establishing connection through PDO
require("database.php");
try{
//querying the firstname data from the people table
$sql = $conn->query("SELECT firstname FROM people");
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
//looping through the array of firstname and echoing it out if it equals to the user input of name. else just echo out sorry no match
while($theRow = $sql->fetch(PDO::FETCH_ASSOC)){
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) && isset($_POST['name']) ){
echo $theRow['firstname'] . "<br />";
}else {
echo 'Sorry no match';
exit;
}
}
?>
the require database.php is just establishing connection to my database using PDO.
I just have 2 rows in my database with
'firstname' of
Jack
Bob
and if in my input field anyone types one of those 2 names php will echo out that name from the people table in the database. Very simple but the only problem I am having is on my else statement I wanted it to echo out Sorry no match if the input field of name is not equal to any name in the database. BUT instead it echo's out Sorry no match once for each name. I understand that I am looping through the array of database name but I only want it to echo Sorry no match once if the name input is not equal to a "firstname" in the database.
EXTRA NOTE:
I have also tried using a foreach loop instead of the while looping with the fetchAll method instead of just fetch but no luck there. Basically gave me the same results.
UPDATE ON THE PROBLEM:
When I load the page the else statement is already taking effect and
echoing out Sorry no match even before I set a name in the input.
and if I type the wrong name it ill echo out Sorry no match twice if
I type the correct name it will echo out the name out of the database
and Sorry no match once.
FIGURED IT OUT:
<?php
$name = $_POST["name"];
require("database.php");
try{
$sql = $conn->prepare("SELECT firstname FROM people WHERE firstname = ?");
$sql->bindParam(1,$name);
$sql->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$theRow = $sql->fetch(PDO::FETCH_ASSOC);
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
echo $theRow['firstname'] . "<br />";
}else{
echo 'no match';
}
?>
Turns out I did not even need a loop do to the WHERE claus only getting the firstname that matched $_POST['name'] so it was just a matter of when to out put that data and that was when the if statement came in. But if I had to output more than one single data I would of probably used a foreach loop like so:
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
echo $row . "<br />";
}
}else{
echo 'no match';
}
If anyone sees any problem with this code or my method please do let me know. Thank you
Firstly, you seem to answer your own question: Why is the else statement running the code twice? Ans: it's not; it's running it once for each iteration of the loop, because you put it in the loop.
Just change your SQL to:
$stmt = $conn->prepare("SELECT firstname FROM people where firstname = ?");
$stmt->execute(array($name));
$result = $stmt->fetchAll();
And it'll either return 1 or 0 rows. So your if statement will look like this:
if($result->num_rows) // True if num_rows > 0; else false
And put your while loop inside your if statement. Keep your else statement to just echo 'Sorry no match';.

mysql_fetch_array() not spiting anything

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/>";
}
?>

How to get a value from database for validation purpose in PHP?

I have a user level field in my database that contains either 1 or 2. what I want to do is to get the row that has the username that I inputted that contains level 2. Here is my code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM order");
while($row=mysql_fetch_array($tbl))
{
if (($row['level']=='2')&&($row['username']==$_POST['user']))
{
echo $row['username']."".$row['garlique']."".$row['rightcee'];
echo $row['oleia']."<br />";
}
else
{
echo $row['username']."".$row['garlique']."".$row['rightcee'];
echo .$row['oleia']."<br />";
}
}
?>
When I tried to test it, an error "unexpected $end" showed. What I think is wrong in my code is the validation if.. ($row['level']=='2').. I don't have any idea how to fix this kind of problem. I am a beginner in php, so if you could help me out, I would appreciate it very much. :)
Close your while loop with }. Syntax error.
I'd like to make a suggestion. If your goal is, as stated, to retrieve the row of the given username that is level 2, your query could do all the work:
// Put the username in a variable, making sure it's safe for SQL by escaping it
$username = mysql_real_escape_string($_POST['user']);
// Grab the row from the table, expecting only a single result
$tbl = mysql_query("SELECT * FROM `order` WHERE `username` = '$username' AND `level` = '2' LIMIT 1");
// Set your row variables
$rows = mysql_fetch_array($tbl);
$row = $rows[0];
if (!$row)
{
// Either not a valid username or the username isn't level 2
}
else
{
// Valid row
}
You forget the last }
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM order");
while($row=mysql_fetch_array($tbl))
{
if (($row['level']=='2')&&($row['username']==$_POST['user']))
{
echo $row['username']."".$row['garlique']."".$row['rightcee']."".$row['oleia'];
echo "<br />";
} else {
echo $row['username']."".$row['garlique']."".$row['rightcee']."".$row['oleia'];
echo "<br />";
}
} // PAY ATTENTION TO THIS!!
?>

Categories