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';.
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.
I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.
I've been on this for some days now. At first I thought the problem was in binding the parameters but I've simplified back to a basic mysqli page and still can't find the error. I'm passing the key for one of the rows in the search page before this onto this page so that I can show more details of the item which was selected.
I added an echo to test the the isset which prints correctly, also it puts the Key into the URL. If I leave out the WHERE Key = '$Key' it prints out the entire dataset. If I replace $row['Key'] with $Key it prints the whole dataset but with the selected key on every row.
This tells me that it is passing the key correctly and the print function is correct. I've tried using WHERE Key = $_GET['Key'] as well as $Key but neither work. I must be doing something basicly wrong here but after three days of trying every variation on the code I can think of, I have no more ideas.
<?php
$mysqli = new mysqli('localhost','user','password','database');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if(isset($_GET['Key'])){
$Key = $_GET['Key'];
echo "Got it";
}else{
echo "No input";
}
$results = $mysqli->query("SELECT * FROM engravers WHERE Key ='$Key'");
$img_url = "http://www.xxxxx.net/images/";
print '<table border="1" >';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["Key"].'</td>';
print '<td>'.$row["Country"].'</td>';
print '<td>'.$row["Year"].'</td>';
print '<td>'.$row["Description"].'</td>';
print '<td>'.$row["Engraver1Surname"].'</td>';
print '<td>'.$row["Designer1Surname"].'</td>';
print '<td>'.$row["Printer"].'</td>';
print '<td>'.'<img src="'.$img_url.$row['Images'].'" />'.'</td>';
print '</tr>';
}
print '</table>';
$results->free();
$mysqli->close();
?>
</body>
There are many SQL column names you should avoid. Please read: http://technet.microsoft.com/en-us/library/ms189822.aspx
Same Reserved Keywords are in MySQL.
If you use one of those just cover it with ``
$results = $mysqli->query("SELECT * FROM `engravers` WHERE `Key`='$Key'");
In your query you are using column key which is not allowed because this is a reserved keyword.
Man, you're already using mysqli, why are you still interpolating variables in your query? This is the way to pass a string $Key to the parser
$results = $mysqli->prepare("SELECT * FROM engravers WHERE `Key`= ?");
$results->bind_param("s", $Key);
while($row = $results->fetch_assoc()) {
... stuff ...
}
If that doesn't work, I'm sure it's not because the prepared statement is the problem.
PD: key is a reserved word, so please note the fieldname is wrapped in backticks.
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/>";
}
?>
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!!
?>