Undefined variable: in PHP - php

I'm a fairly new programmer, especially in PHP as i have come from a VB environment.
Below is the function I am having troubles with, as you can see i have had quite a few attempts (in comments). I thought id leave the comments there in case i'm closer with my other attempts.
I have never used PDO before and as you can see this function pretty much allows the user to log in.
The line if($temp == $_POST['password']) is where the problem is. Apparently $temp is undefined, but i cannot see why, i have even declared it at the top of the function to be sure. Anyone have any ideas?
public function load_user_data() {
$temp;
$sql;
try{
// $STH = dbHandler::$DBH->prepare("SELECT * FROM tblCustomer WHERE email = :email");
// $STH->bindValue(':email', $this->email);
// $STH->execute();
// $posts = $STH->fetch(PDO::FETCH_ASSOC); //If only fetch 1 line use just "fetch" instead of "fetchAll"
// echo '<pre>';
// print_r($posts);
// echo '</pre>';
//--------
$STH = dbHandler::$DBH->prepare("SELECT password FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $_POST['usermail']);
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
$temp = $row;
}
//$temp = $STH->fetch(['password']);
// while($row = $STH->fetch()) {
// $temp = $row['password'];
// }
//--------
// $sql = "SELECT password FROM tblCustomer WHERE email = :email";
// $stmt = $PDO->query($sql);
// $row = $stmt->fetchObject();
// $temp = $row->password;
if($temp == $_POST['password']) {
$STH = dbHandler::$DBH->prepare("SELECT * FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $this->email);
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo("we have reached here");
while($row = $STH->fetch()) {
$firstname = $row['firstName'];
$lastname = $row['secondName'];
$title = $row['title'];
$companyname = $row['companyName'];
$email = $row['email'];
$phone = $row['phone'];
$email = $row['mobile'];
$startdate = $row['startDate'];
$isauthorised = $row['isAuthorised'];
$accstop = $row['accStop'];
$stopdate = $row['stopdate'];
}
}
}
catch (PDOException $e) {
print $e->getMessage();
}
}

The problem is here:
$STH = dbHandler::$DBH->prepare("SELECT password FROM tblCustomer WHERE email = :email");
$STH->bindValue(':email', $_POST['usermail']);
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
$temp = $row;
}
First, you need to do:
$STH->execute();
before you try to fetch rows.
Second, if the query doesn't match any rows, your while loop will never go into the body, so $temp will not be set. Since you apparently only expect to get one row from the query, you don't need to use while. Instead, do:
if ($temp = $STH->execute()) {
// all the code that depends on finding a row goes here
...
}
Inside that block, you'll need to do:
if ($temp['password'] == $_POST['password'])

Related

PDO While loop only gets the last data

I am trying to display a nested json as seen in this picture
JSON Ouput
However it only gets the last data. I am sure that the 1st id has a data. Please see the code below
<?php
include 'conn2.php';
$pdo = new PDO($dsn, $user, $passwd);
$stmt = $pdo->prepare("CALL sp_foods_display();");
$stmt->execute();
$stmt->bindColumn('bar_name',$bar_name);
$stmt->bindColumn('address',$address);
$stmt->bindColumn('id',$post_id);
$response = array();
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp["bar_name"] = $bar_name;
$temp["address"] = $address;
$temp["item_details"] = getItem($post_id);
array_push($result, $temp);
}
$response["result"] = $result;
echo "<pre>" . json_encode($response,JSON_PRETTY_PRINT) . "</pre>";
function getItem($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM fct_menu_foods WHERE post_id = :cur_post_id ORDER BY id ASC");
$stmt->bindParam(":cur_post_id",$id,PDO::PARAM_INT);
$stmt->execute();
$food_details = array();
$stmt->bindColumn('food_name',$food_name);
$stmt->bindColumn('price',$price);
$stmt->bindColumn('img_name',$img_name);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
$temp = array();
$temp["food_name"] = $food_name;
$temp["price"] = $price;
$temp["img_name"] = $img_name;
array_push($food_details, $temp);
}
return $food_details;
}
?>
my target output is to display all data in nested.
I found a solution. My bad. You have to closeCursor(); for every query and use fetchAll for getting the data.

Run php action for every element

I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.

fetch multiple rows of same id in different variable

I have two rows contaning data of same id.
It has different adresses in different rows for the same id.
I want to fetch both the adress in different variable in php.
How can i do this? Please help!
Below is the code:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
It gives me both the address of the same id in one variable only.
I want them in two different variables.
You are already getting an array of addresses in $d.
What you can do is:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
If you have address ids 2 and 4, you will get two variables
$ad_2 and $ad_4
You should use parameterized queries. Use PHP's PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Don't want your queries getting injected with attacks.
I suggest you to use mysqli instead.
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
and then
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
you can verify it:
print_r($data);

PHP SQL Not updating row in database

I'm currently making a simple script that takes a user input named comments and putting it in a database. Every time I use the same email, I want it to overwrite their last entry. However, it keeps putting a new entry every time. Here is my code:
if($comments){
try{
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "TRUE";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
catch(Exception $e){}
}
elseif($optout=="false"){
echo "<img width=\"245\" height=\"130\" src=\"logo.png\"/><br/>";
echo "<h1>Thank you. You should receive your order on xx-xx-xx</h1>";
$TF = "FALSE";
$comments = "";
if($numrows == 0){
$postquery = "INSERT INTO TTT25 (email,card,changes,comments) VALUES ('$email','$businesscard','$TF','$comments')";
$querythepost = sqlsrv_query($conn, $postquery);
}
else{
$postquery = "UPDATE TTT25 SET changes = '$TF', comments = '$comments' WHERE email = '$email'";
$querythepost = sqlsrv_query($conn, $postquery);
}
}
Sorry it must have cut off:
my num rows and other variables defined before the conditional statements:
$optout = $_GET['opt'];
$encodedemail = $_GET['email'];
$email = base64_decode($encodedemail);
$originalcard = base64_decode($_GET['card']);
$businesscard = $originalcard;
$comments = $_POST['comments'];
//$primary = md5(uniqid(rand (), true)); no longer needed
$postquery;
$TF;
$sqlmatch = sqlsrv_query("SELECT * FROM TTT25 WHERE email = '".$email."'");
$numrows = sqlsrv_num_rows($sqlmatch);
echo $numrows;

Reason for: Trying to get property of non-object in php

if(isset($_POST['uname']))
{
$query = "SELECT * FROM user_info";
$res = $mysqli->query($query);
$num = $res->num_rows;
$i = 0;
$cpwd = $_POST["pswd"];
$hpwd = SHA1($cpwd);
$tmp = $_POST["uname"];
while($i < $num)
{
$row = $res->fetch_object();
$name = $row->Username;
$pwd = $row->Password;
if($name == $tmp)
{
//check if user is blocked
}
//hashed pwd
if($pwd == $hpwd)
{
//success
exit();
}
//request for pwd change
else if($pwd == $cpwd)
{
//change
exit();
}
else if($pwd != $hpwd)
{
//incorrect pwd
}
}
$i++;
}
if($i == $num)
{
//new user
}
}
I'd guess that you're somehow looping past the end of the array and $row is actually NULL.
So $res->fetch_object() did not return an object. Take a look at the documentation of this function. What does it return when it finds nothing?
some times num_rows return 1, even if no rows effected. Try to use
while($row = $res->fetch_object())
or
you forget to increment $i :)
get rid of that junk and make it like this
$query = "SELECT * FROM user_info WHERE Username = ? AND Password = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $_POST["uname"], SHA1($_POST["pswd"]));
$stmt->execute() or trigger_error($mysqli->error());
if (!$mysqli->affected_rows) {
//no such user
}
I've never used mysqli myself, so, there may be typos.
But I hope you'll be able to get the idea.

Categories