SQL query in php function 500 server error [duplicate] - php

This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 7 years ago.
I ran into a very strange thing.
This throws an 500 server error:
function writeMsg() {
$id='0000000625';
$translation = 'word';
try {
$stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
$stmt->execute(array($translation,$id));
$response["success"] = 1;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response["success"] = 0;
}
echo 'RESPONSE: '.$response["success"];
}
writeMsg();
This runs fine:
$id='0000000625';
$translation = 'word';
try {
$stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
$stmt->execute(array($translation,$id));
$response["success"] = 1;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response["success"] = 0;
}
echo 'RESPONSE: '.$response["success"];
I only removed the first and the last 2 lines.
Does anyone has an explanation to this?

You've probably missed the $conn variable scope
function writeMsg() {
global $conn;
$id = '0000000625';
$translation = 'word';
try {
$stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
$stmt->execute(array($translation, $id));
$response["success"] = 1;
} catch(\PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response["success"] = 0;
}
echo 'RESPONSE: ' . $response["success"];
}
writeMsg();
Just use global $conn to retrieve the $conn variable from the global scope. Check more at http://php.net/manual/en/language.variables.scope.php for global keyword

Related

PHP 7.x SQLITE3 PDO - is the execute() closing the PDO connection?

I have this code that works weird with SQLITE3 , since the same code with MYSQL works fine
The issue is the line commented with "ISSUE" at line #31, because with MYSQL/MariaDB that "re connection" is NOT needed
Now I better explain
If the IF routine is not entered, I have NO error
If the IF routine is processed, line #34 throws
Uncaught Error: Call to undefined method PDOStatement::prepare()
like if the $PDO-execute(); inside the IF is destroying the PDO istance
You may say, well, no problem, now you have fixed it ... yes, but I'd like to understand why this happen.
Also portability is a point. If this is PDO ... except for the connection, the rest of the script should work and moved among various supported PDO DBs
Thank you if you kindly hint what is the reason and what is it
<?php
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$PDO = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$PDO->bindValue(':testo', $_POST['NoteUpdateText']);
$PDO->bindValue(':id', 1);
$PDO->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
$PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$PDO = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$PDO->execute();
$row = $PDO->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
FIXED CODE
<?php
//include 'db-con2.php';
// table: ajax
// col: testo
// Create or open a database file
$PDO = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$statement = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
$statement->bindValue(':testo', $_POST['NoteUpdateText']);
$statement->bindValue(':id', 1);
$statement->execute();
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br> - IF -" . $e->getMessage();
}
}
// carica da DB in ogni caso per caricare il P col testo realmente in DB
//$PDO = new PDO('sqlite:myDatabase.sqlite3');
try {
$statement = $PDO->prepare('SELECT testo FROM ajax WHERE id=1 LIMIT 1');
$statement->execute();
$row = $statement->fetch();
//var_dump($row);
echo $row["testo"];
}
catch(PDOException $e)
{
echo $sql . "<br> - NORMALE - " . $e->getMessage();
}
?>
Why would you override $PDO variable ?
$pdo = new PDO('sqlite:myDatabase.sqlite3');
if( isset($_POST['NoteUpdateText']) && !empty(trim($_POST['NoteUpdateText'])) ){
//$testo = $_POST['NoteUpdateText'];
try {
$stmt = $PDO->prepare('UPDATE ajax SET testo = :testo WHERE id = :id');
if ($stmt->execute(array(':testo'=>$_POST['NoteUpdateText'], ':id' => 1)))
{
// echo a message to say the UPDATE succeeded
//echo $stmt->rowCount() . " records UPDATED successfully";
} else {
// There's error processing updates
// debug
print_r($stmt->errorInfo());
}
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
// In EVERY case, load the actual DB record and return it to javascript
// There's no need to redeclare $PDO
// $PDO = new PDO('sqlite:myDatabase.sqlite3'); // --- ISSUE, theoretically this is already opened at line #3 ---
try {
$stmt = $pdo->prepare("SELECT testo FROM ajax WHERE id=1 LIMIT 1"); // line #34
$stmt->execute();
$row = $stmt->fetch();
//var_dump($row);
echo $row["testo"];
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

Catch exception from inside class [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I am little confused with try catch concepts.
I have this code in PHP.
<?php
while (true) {
try {
foreach ($data as $message) {
$functionToCall = new functions();
$functionToCall->remove($data);
}
} catch (Exception $e) {
echo "This is inside catch";
echo 'Message: ' . $e->getMessage();
}
}
class functions
{
public function __construct()
{
$this->dbConnection = pg_pconnect("host = $hostname port=$port dbname = $database user = $username password = $password")
or die("Can't connect to database" . pg_last_error());
}
public function remove($data)
{
$query = "UPDATE table
SET isDeleted = true;
$res = pg_query($this->dbConnection, $query);
if (!$res) {
print_r(error_get_last());
throw new Exception(error_get_last(), 1);
}
}
}
I made a slight change with code to throw an exception I added
unset($this->dbconnection);
after
$query = "UPDATE table
SET isDeleted = true;
to throw an exception. Exception is thrown but My catch is not catching this exception.
How can I catch this error?
Thanks
Looks like a syntax issue if that's the actual code, try this edit:
public function remove($data)
{
$query = "UPDATE table SET 'isDeleted'= true";
$res = pg_query($this->dbConnection, $query);
if (!$res) {
print_r(error_get_last());
throw new Exception(error_get_last(), 1);
}
}
Notice the quote mark changes around: $query = "UPDATE table SET 'isDeleted'= true";
Your exception logic was being parsed as a string it seems.
Notice your code doesn't close the string on $query ...
$query = "UPDATE table
SET \"isDeleted\" = true;
$res = pg_query($this->dbConnection, $query);
if (!$res) {
print_r(error_get_last());
throw new Exception(error_get_last(), 1);
}

getting variables outside if statement

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.

PHP MySQL Select script

I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;

Mysql adds new row instead of updating it

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.

Categories