Hi guys I have a problem with getting a variable outside and after an if statement. Little code explanation: $gameid or $id is sent via ajax to this file. Now $id have always a value and if (isset($_GET['id'])) { is true. The insert and select querys work very well. The problem is that I cant get the variable $answer or $question[0]['question']; after the second if statement. I can get them when I change the second if (isset($_GET['id'])) { to else { but then anyhow there become two rows in my database inserted, the first is right and the second one is empty. Now why cant I get the variables $answer and $question[0]['question']; after the second if condition?
The error log shows: Notice undefined variable question.
<?php
$hostname='localhost';
$user='';
$password='';
if (isset($_GET['gameid'])) {
$gameid = $_GET['gameid'];
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
echo $id;
}
if (isset($_GET['questionid'])) {
$questionid = $_GET['questionid'];
}
$new = 0;
if (isset($_GET['gameid'])) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT *
FROM questions_de
WHERE id = '$questionid'
LIMIT 1";
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$question = $res->fetchAll();
}
if($question > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
if ($question[0]["answerm²"] == 0 && $question[0]["answerm³"] == 0) {
$answer = "answer_m";
} else {
$answer = "answerm³";
}
}
if (isset($_GET['id'])) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT username
FROM user
WHERE id = '$id'
LIMIT 1";
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$user2name = $res->fetchAll();
}
if($user2name > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT *
FROM questions_de
LIMIT 1"; //
if ($res = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$question = $res->fetchAll();
}
if($question > 0) {
//do something
} else {
echo "Sorry something happen wrong with our servers.";
}
}
catch(PDOException $e) {
}
if ($question[0]["answerm²"] == 0 && $question[0]["answerm³"] == 0) {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO game_create (user1, user2, user1name, user2name, question, questionid, answer)
VALUES ('".$_COOKIE["userid"]."', '".$id."', '".$_COOKIE["username"]."', '".$user2name[0]["username"]."', '".$question[0]['question']."', '".$question[0]['id']."', '".$question[0]['answer_m']."')";
if ($dbh->query($sql)) {
//echo "New Record Inserted Successfully";
} else{
// echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0) {
} else {
echo 'Sorry something went wrong.';
}
$answer = "answer_m";
}
else {
try {
$dbh = new PDO("mysql:host=$hostname;dbname=max_com_db_socame",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO game_create (user1, user2, user1name, user2name, question, questionid, answer)
VALUES ('".$_COOKIE["userid"]."', '".$id."', '".$_COOKIE["username"]."', '".$user2name[0]["username"]."', '".$question[0]['question']."', '".$question[0]['id']."', '".$question[0]['answer_m³']."')";
if ($dbh->query($sql)) {
//echo "New Record Inserted Successfully";
} else{
// echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0) {
} else {
echo 'Sorry something went wrong.';
}
$answer = "answerm³";
}
}
?>
On the line:
if (isset($_GET['gameid'])) {..}
You're checking if the $_GET['gameid'] is set, with other words, if it has a value. As you stated, $_GET['gameid'] only has a value when $_GET_[id] doesn't have value. As you said, $_GET_['id] always has value, so $_GET['gameid'] wont be initialized.
Therefor, it won't get past this condition, and won't reach the line of $question = $res->fetchAll();, which initializes the variable.
The same thing stands for $answer, since it's in the same if statement and is also doing conditional checking on the $question variable.
To solve this problem, either initialize the $_GET['gameid'] variable by sending it to the PHP script without any conditions or remove the if (isset($_GET['gameid'])) {..} statement.
Related
I have three queries on my login script. One select query checks the users' credentials, another to update the last login, and the third one is a select query to see whether the user exists in another table, so if the user exists in the table, go some where. If the user doesn't exist, go somewhere else.
The third query is the one is acting weird. Below:
require_once '../includes/sessions.php';
//echo 'hello';
$employerlogindata = $_POST['employerlogindata'];
$data = json_decode($employerlogindata);
$employeremailfromjs = $data->employeremail;
$employerpasswordfromjs = $data->employerpassword;
//sanitization
$employeremail = htmlentities($employeremailfromjs);
$employerpassword = htmlentities($employerpasswordfromjs);
//PHP validation rules
$validflag = true;
function checkblanks($variable){
if($variable == ''){
$validflag = false;
print_r('Empty Inputs. Please try again.');
}else {
$variable = trim($variable);
$variable = stripslashes($variable);
return $variable;
}
}
checkblanks($employeremail);
checkblanks($employerpassword);
if($validflag == false) {
echo 'You have problematic entries. Try again.';
} else {
try{
$sql = "SELECT EID AS dbeid, EMPLOYER_EMAIL AS dbemail, `PASSWORD` AS dbpwd, EMPLOYER_NAME AS dbcompanyname, LAST_LOGIN AS dblastlogin FROM userpwd WHERE EMPLOYER_EMAIL = :employeremail;";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
//echo "select statement successfully executed";
//echo $sql;
} catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
//echo $query->rowCount();
if ($query->rowCount() == 0){
echo "Email/Password combo was not found in the system.";
}else {
$result = $query->fetch(PDO::FETCH_OBJ);
//print_r($result);
$dbeid = $result->dbeid;
$dbemail = $result->dbemail;
$dbpwd = $result->dbpwd;
$dbcompanyname = $result->dbcompanyname;
$dblastlogin = $result->dblastlogin;
//echo $dbeid;
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid;
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
echo "Email/Password combination is invalid. Please Try Again.";
}
try{
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
$stmt->execute();
}catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$res = $stmt->fetch();
$eid = $res['EID'];
$count = $stmt->rowCount();
if($stmt->rowCount() == 1){
echo "employerdashboard.php $eid $count";
$stmt->closeCursor();
} else if ($stmt->rowCount() == 0){
echo "e_profile.php $eid $count";
$stmt->closeCursor();
}
}
}
?>
After a set of login credential is successful, the script hits both the second and the third queries. However, the third query takes on the results of the previous ran query. After a second click on the frontend with the same credentials, it produces the right results.
I thought maybe I could find the functionality of mysqli_free_result() in PDO's closeCursor, but that doesn't work. I want it to produce the right result the first time.
Any clues as to why this is happening?
Your variable is out of date (or at least that is my theory), as I said in the comments.
If you have
global $sessemployerid = $_SESSION['EID'];
Then you do
$_SESSION['EID'] = $dbeid;
Then you use $sessemployerid it will not be equal to $_SESSION['EID'] = $dbeid. It will be equal to the previous value of the session when it was assigned, which may or may not be correct. Probably on the first attempt it is wrong, then on subsequent attempts it is correct.
Just to lay it out a bit further:
//you assign $sessemployerid way up here
global $sessemployerid = $_SESSION['EID'];
...
//then you update the session
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid; //<--- here you update the session but neglect $sessemployerid
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
....
//then you use $sessemployerid, but it has a stale value (sometimes)
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
To fix this you could use a reference assignment
global $sessemployerid =& $_SESSION['EID'];
This can be demonstrated by this simple code:
$a = 1;
$b =& $a; //initial assignment, with reference
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is auto-magically updated
See it here
Ouputs
1
2
If you do it this way (the "normal" way)
$a = 1;
$b = $a; //initial assignment, normal
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is not updated
The output is
1
1
Alternatively you could simply update the global after changing the session's value:
if(password_verify($employerpassword, $dbpwd)){
...
$_SESSION['LAST_LOGIN'] = $dblastlogin;
global $sessemployerid = $_SESSION['EID'];
}else{
...
Because the value of $sessemployerid is out of sync with $_SESSION['EID'] you will get inconstant behavior depending on if you had updated the session or not on a previous page attempt.
Hope that makes sense.
I have a PDO that is querying a non-existant user in the database to handle user registration. The problem is, var_dump and print_r both do not print anything if the user is not found.
try {
$stmt->execute();
while($row = $stmt->fetch()) {
var_dump($row);
print_r($row);
if($row = null) { // Not working
# if(!isset($row)) { // Not working
# if(empty($row)) { // Also not working
echo "User not found";
} else {
echo $row['realname']."<br>";
}
}
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
What is happening here? The page is just blank.
php -l index.php repors no syntax errors and the page is not throwing error 500.
Nothing in view source either.
Here is connection details:
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=PHP_PDO', "root", "root", array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
} catch(PDOException $e) {
die("FATAL ERROR OCCURED");
}
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATA BASE
The reason why it's not working, is that you are "assigning" in if($row = null) using 1 equal sign, rather than "comparing" if($row == null) with 2 equal signs (or 3 "if identical", depending on what you want to check for).
Consult: The 3 different equals here on Stack about this.
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
PHP sees the "assignment" as being valid syntax and that is why you are not receiving any errors.
Turns out i had to reorganize the code a bit.
I took the $row = $stmt->fetch(); out of the while loop, and checked the $row seperately. Like this:
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATABSE ON PURPOSE
try {
$stmt->execute();
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
$res = $stmt->fetchAll(); # Replaced fetch() with fetchAll()
if(empty($res)) {
echo "User not found";
} else {
foreach($res as $row) { # replaced while() with foreach()
echo $row['realname'];
}
}
I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.
I have a table in MY SQL that may either have an entry in a certain column as 1 or > than 1. Basically based on the current Value of the Entry in the column I would wish to run either of two methods:
Part code:
$db->prepare("SELECT vote_count FROM tbl_voter_count WHERE voter_phone_number = :phone ");
$sql->bindParam(":phone", $phone );
try {
$sql->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
if($data){
foreach ($data as $row) {
$count = $row['vote_count'];
if($count == 1)
{
//Logic 1
}
//Logic 2
}
Based on the above,is there a better way of aciving this with far much less code entanglement and Lines.?
try {
$sth->execute();
foreach($sql->fetchAll(PDO::FETCH_ASSOC) as $row) {
if($row['vote_count'] == 1) {
//Logic 1
} else {
//Logic 2
}
}
} catch ...
edit
I'd recommend using the catch at the end of the request.
Your method is fine. You can also do:
$db->prepare("SELECT vote_count > 1 as multivote FROM tbl_voter_count WHERE voter_phone_number = :phone ");
$sql->bindParam(":phone", $phone );
try {
$sql->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
while ($row = $sql->fetch(PDO::FETCH_ASSOC) {
if ($row['multivote']) {
//Logic 1
} else {
//Logic 2
}
}
Why would it not work to call the get_accounts() function at the end of the delete_account() function?
function get_accounts() {
require(ROOT_PATH . "inc/database.php");
try {
$results = $db->query("SELECT * FROM account");
} catch (Exception $e) {
echo ("ERROR: Data could not be retrieved from the database." . $e);
exit;
}
$accounts = $results->fetchall(PDO::FETCH_ASSOC);
return $accounts;
}
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
echo($deleteAccount);
get_accounts();
};
Basically, I want to run the delete_accounts() function and at the end I would like to run the get_accounts() function, which will refresh the list of accounts on the page after the selected account has been deleted. I can't seem to call a function from within another function, no matter what I try.
Use the finally part of the try catch & remove the 'exit();'
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
}finally{
get_accounts();
}
echo($deleteAccount);
}