Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...
$username="xxx";
$firstname="xxx";
$check=0;
if (isset($_GET['u'])){
$username=strip_tags(#$_GET['u']);
if (ctype_alnum($username)){
$check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
$stmt->execute(array($username));
$check=$stmt->fetchAll();
if(count($check)==1){
$get=$stmt->fetch(PDO::FETCH_BOTH);
echo "$get";
$username =$get["username"];
$firstname = $get["first_name"];
}else{
echo "<h2> User does not exist!</h2>";
exit();
}
}
}
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.
if (count($check) == 1) {
$get = $check[0];
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Or you could just replace the fetchAll with fetch.
$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).
Related
How do I get fname from the result of SQL query and store it in $_SESSION['fname'].
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
This is my php code to get the count and fname(username) from database using sql query
init.php has the connection details
my aim here is to retrieve fname using emailid and password
i get the count which is always 1 as per my database restrictions and a fname i want to declare a session variable as this fname
how do i decode the array to get fname
thanks in advance
Seems that you don't assign a value to $fname
<?php
include('init.php');
session_start();
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$fname="";
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result){
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
//
// try assign $fname here if you want the first you can
//
if($fname ==""){
$fname = $row[1];
}
//
}
$_SESSION["fname"]=$fname;
echo json_encode(array("server_response"=>$response),JSON_FORCE_OBJECT);
}
else{
echo "error";
}
mysqli_close($con);
}
?>
Since you are making an associative array, you need to access Count and name as keys. Like:
foreach($response as $key => $value) {
echo "Key=" . $key . ", Value=" . $value;
echo "<br/>";
}
But if you are sure that you will always get a single row, why don't you just store them in scalar variables like $count and $fname and inside your code do this:
$count; $fname = "";
while($row=mysqli_fetch_array($result))
{
$count = $row[0];
$fname = $row[1];
}
When execute the query it's not working, it will print error. $q also not coming when i'm print it. but $_SESSION["username"]; is working?
<?php
session_start();
$_SESSION["username"];
include 'Db_Connection.php';
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES ('$username',NOW(),'$q')";
$result = mysqli_query($con,$sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
?>
Couple of things I can pick up from your provided code.
Your second line $_SESSION["username"]; is superfluous as it does nothing
You are using the mysql_* functions which are deprecated
You are not using prepared statements for inserting variables into your query
try something like this:
session_start();
//start assuming this is in your connection file
$con = new mysqli("db-ip-address", "db-user", "db-pass", "db-name")
//end assuming
$q= $_GET[q];
$username= $_SESSION[username];
echo $username;
echo $q;
$sql="INSERT INTO search(searcher,searched_time,searched_email) VALUES (?,NOW(),?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $username, $q);
$result = $stmt->execute();
if($result) {
echo "Success";
} else {
echo "Error";
}
//remember to cleanup connections etc
as far as the value $q not printing out, make sure that the value is set via the GET query string http://someurl.com/somefile.php?q=some-value and that $q is not some weird non-printable value. If you want to confirm that the value is set, try running var_dump($_GET) to output the contents of your $_GET array to ensure there is actually a value being set.
I believe this is your problem:
$q= $_GET[q];
q should be surrounded in quotes, e.g.:
$q = $_GET['q'];
Other than that, what Damon said was completely correct.
I'm sorry if this has been asked, but I have no idea what to search for to find an answer.
I'm just starting to learn PHP and am doing a simple tutorial where I'm "logging into" a data base (just checking to see if the email and password match what is stored no actual session is being created).
I have this code:
<?php
include("connectToDb.php");
$loginEmail = $_POST['loginEmail'];
$loginPassword = $_POST['loginPassword'];
$query = mysqli_query($dbc, "SELECT * FROM users WHERE email='$loginEmail'");
$numrows = mysqli_num_rows($query);
if($numrows != 0)
{
while($row = mysqli_fetch_array($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbfirstname = $row['firstName'];
}
if($loginEmail == $dbemail)
{
if ($loginPassword == $dbpassword)
{
echo "Hi ".$row['firstName'].", you are now logged in.";
}
else
{
echo "login failed.";
}
}
}
mysqli_close($dbc);
?>
But the $row['firstName'] in the echo statement prints as a blank string: "Hi , you are now logged in.". If I use the exact same code but repalce $row['firstName'] with $dbfirstname in the echo statement, I get a properly formatted message "Hi Jason, you are now logged in.".
Those two variables are supposed to be the same... why does one work while the other does not?
Check the control flow:
You have the while loop while($row = mysqli_fetch_array($query)) - so you assign a new value to $row and test it. If it evaluates to false (i.e. no more rows), you break the loop.
This implies, that after the loop $row no longer has valid content. Your stored values (e.g. $dbfirstname) are from the previous iteration of the loop and thus contain valid data.
i've got a problem with my php script. I want to check my script if there is anything in array and if there's no to echo a message but when array is empty it just don't echo nothing.
That's my code:
include("mysql_connect.php");
$name = $_POST['playerName'];
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if($name==""){
echo 'Type in player name!';
}else{
while($usersList= mysql_fetch_assoc($users)){
if(!array_count_values($usersList)){
echo 'Player not found';
}else{
echo $usersList['username'].', ';
}
}//While end.
}//If name is empty end.
As mentioned, you have to check for rows before the loop.
$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
foreach() {
The problem seems is that, if a user enters a invalid name, the while loop does not execute, as the query simply cannot find any rows, the code should be as follows
include("mysql_connect.php");
$name = $_POST['playerName'];
if( $name === "" ){
echo 'Type in player name!';
} else {
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if ( mysql_num_rows($users) == 0) {
echo "Invalid Player name provided";
} else {
while($usersList= mysql_fetch_assoc($users)){
{
echo $usersList['username'].', ';
} //While end.
}
}//empty name
Notes:
I have re-formatted the code as it looked ugly
The query is executed only if a user provides some text for name, why execute the query when the name is empty !
instead of
if(!array_count_values($usersList)){
use
if(empty($usersList)){
Your while loop wont be executed if $users is empty, so the condition:
if(!array_count_values($usersList)){
echo 'Player not found';
}
will never be met because it is contained in a loop which will never run.
I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James