I'm using a PDO driver to connect to a mySQL database. I have had luck querying this database when I search by ID; however, when I try to change the query from ID to first_name, I just get an error. Below is my code:
This code works
//functions.php file
function query_database($id) {
include("connection.php");
try {
$results = $db->query("SELECT first_name, last_name FROM master_tradesmen WHERE id = $id");
}catch(Exception $e) {
echo "Something went wrong with the query.";
}
$data = $results->fetch();
return $data;
}
$res = query_database(1);
print_r($res);
This returns:
Array ( [first_name] => Steve [0] => Steve [last_name] => Albertsen [1] => Albertsen )
So now, instead of searching by ID, I just want to search by first name. Here is the slightly altered code:
function query_database($name) {
include("connection.php");
try {
$results = $db->query("SELECT first_name, last_name FROM master_tradesmen WHERE first_name = $name");
}catch(Exception $e) {
echo "Something went wrong with the query.";
}
$data = $results->fetch();
return $data;
}
$res = query_database('Steve');
print_r($res);
This returns the following error:
Notice: Undefined variable: results in /home/locompre/public_html/php/functions.php on line 12
Fatal error: Uncaught Error: Call to a member function fetch() on null in /home/locompre/public_html/php/functions.php:12 Stack trace: #0 /home/locompre/public_html/php/functions.php(16): query_database('Steve') #1 {main} thrown in /home/locompre/public_html/php/functions.php on line 12
Any insight into why this might be happening?
You're open for SQL injections! The error happens because you initialize the variable result inside the try block. The variable isn't accessible outside the try-catch block if a error occurs, which is fact because strings need to be wrapped with single quotes in a SQL query!.
A better way to do it is:
function query_database($name) {
include("connection.php");
try {
$stmt = $db->prepare("SELECT first_name, last_name FROM master_tradesmen WHERE first_name = :name");
$stmt->bindValue(':name', $name);
$stmt->execute();
$data = $stmt->fetchAll();
return $data;
}catch(Exception $e) {
echo "Something went wrong with the query.\n<br>".
"Error: \n<br>" . $e->getMessage() . "\n<br>" .
"StackTrace: \n<br>" . $e->getTraceAsString();
return null;
}
}
$res = query_database('Steve');
print_r($res);
Related
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 the below snippet of code. When I run the whole program, it fails at this section with the error Fatal error: Call to a member function fetch() on a non-object in <filename> on line 26. I'm really not sure what I should do to fix the problem. If it matters, I ran the SQL query against my database and it returns exactly what it should.
if(isset($_POST['submit'])) {
$query = 'SELECT email FROM users WHERE email=:email';
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $conn->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $ex) {
echo $ex->getMessage();
}
$row = $result->fetch(); //fails on this line
if(empty($results)) {
$passset = 1;
}
}
PDOStatement::execute returns TRUE or FALSE, not a result object.
Change this:
$row = $result->fetch();
To this:
$row = $stmt->fetch();
Hey guys im having a little trouble with the PDO in php as the error it is returning is an undefined index. The code for the function and query and return of result is this:
function getUserDetails($user) {
$db = connect();
try {
$stmt = $db->prepare('SELECT name,addr AS address,team
FROM TreasureHunt.Player LEFT OUTER JOIN TreasureHunt.MemberOf ON (name=player)
LEFT OUTER JOIN TreasureHunt.PlayerStats USING (player)
WHERE name=:user');
$stmt->bindValue(':user', $user, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll();
$stmt->closeCursor();
} catch (PDOException $e) {
print "Error : " . $e->getMessage();
die();
}
return $results;
}
However when running the code for the index page i get an error that says Notice: Undefined index: name
The Code for the index is this:
try {
$details = getUserDetails($_SESSION['player']);
echo '<h2>Name</h2> ',$details['name'];
echo '<h2>Address</h2>',$details['address'];
echo '<h2>Current team</h2>',$details['team'];
echo '<h2>Hunts played</h2> ',$details['nhunts'];
echo '<h2>Badges</h2>';
foreach($details['badges'] as $badge) {
echo '<span class="badge" title="',$badge['desc'],'">',$badge['name'],'</span><br />';
}
} catch (Exception $e) {
echo 'Cannot get user details';
}
my question is why is it throwing a notice and how do i go around this problem?
fetchAll returns all results (potentially multiple rows) in a multidimensional array:
array(
0 => array(/* first row */),
1 => array(/* second row */),
...
)
That's why the array doesn't have a direct index 'name', it needs to be [0]['name'].
Or you shouldn't fetchAll, just fetch.
Looking on my error log I get the following error a lot:
[01-Mar-2011 04:31:27] exception 'Exception' with message 'Query failed' in /home1/mexautos/public_html/kiubbo/data/model.php:89
Stack trace:
#0 /home1/mexautos/public_html/kiubbo/data/article.php(275): Model::execSQl2('update articles...')
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save()
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking()
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking()
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('')
#5 {main}
If I go to the model.php file I see this:
static function execSQl2($query)
{
/*
Execute a SQL query on the database
passing the tablename and the sql query.
Returns the LAST_INSERT_ID
*/
$db = null;
$lastid = null;
//echo "query is $query";
try
{
$db = Model::getConnection();
$results = $db->query($query);
if(!$results) {
throw new Exception('Query failed', EX_QUERY_FAILED );
}
$lastid = $db->insert_id;
}
catch(Exception $e)
{
/* errors are handled higher in the
object hierarchy
*/
throw $e;
}
Does Anybody see an error, or i should look somewhere else?
Thank you and Regards,
Carlos
Edit:
This is the query: $lastid = parent::execSql2($query);
And this is the context:
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
error_log($e);
}
}
Regards,
Carlos
As heximal said, it's probably an error in your SQL query. Copy and paste the full SQL being queried into PhpMyAdmin or a similar tool and see what errors (if any) come up. Often, the problem is simply a mistyped table or a missing value.
Of course you can also post the query here if you want SO help with it! :D
The error is propably in sql-query. Append to log query text and analyze it.
It appears I can connect to my database using PDO, but can't execute any queries with it. Example:
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
}
catch (PDOException $e) {
die ($e);
}
print_r($link);
$result = $link->query("select * from mt3_users");
var_dump($result);
$row = $result->fetch($result);
die("Your id is: ".$row["id"]);
//$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
if (!$link) {
echo "Failed to connect to $this->sHost!";
return false;
}
return $link;
}
This returns the following:
PDO Object ( ) bool(false)
Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32
So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?
Most likely the query fails, are you sure of the name of the table mt3_users and that you have selected the right database? That error message shows that $result is not an object and that's due to an error in the query.
Also:
$row = $result->fetch($result);
should be
$row = $result->fetch();
unless you want to specify options to fetch(), but you don't pass the object as argument.
Array ( [0] => 00000 [1] => 1046 [2] => No database selected ) Array ( )
Nevermind, I guess. It turns out that while migrating from using regular MySQL functions, I wasn't setting $this->sName ($this->sName was null. I'm half surprised it didn't throw an exception. Only half, though)
Fixed.
But thank you guys for the answers :)
can you give this a try
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$rows = $pdolink->query("select * from mt3_users");
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
and if you need to stick with fetchAll function
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$q = $pdolink->prepare("select * from mt3_users");
$q->exectue();
$rows = $q->fetchAll();
var_dump($rows);
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
In order to get the error in your query:
$result = $link->query(...);
if($result===FALSE){
print_r( $link->errorInfo);
exit();
}
// the correct way to fetch one row
$link->fetch(PDO::FETCH_ASSOC); // or whatever way you want to fetch data