This has annoyed me for a while now. I am trying this query in phpmyadmin.
select `id` from `users` where `fb_id` = 507292797 limit 1
This returns the value 13, so why doesn't this work:
$sql = "select `id` from `users` " .
"where `fb_id` = :fb_id " .
"limit 1";
try
{
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':fb_id', $fb_id2, PDO::PARAM_INT);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
$stmt->closeCursor();
}
catch (Exception $e)
{
die ($e->getMessage() );
}
echo "id: " . $fb_id2 . " var_dump: " . var_dump($user);
exit();
This returns:
id: 507292797 var_dump: bool(false)
When var_dump should return $user['id'] = 13
Can somebody see what I am doing wrong here?
ps. here is my db connection function if that matter
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$driver_options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8' );
try
{
$this->db = new PDO($dsn, DB_USER, DB_PASS, $driver_options);
You are doing things in this order :
Preparing the statement
Binding the variables
Trying to fetch data from the statement
Executing the statement
The two last steps should be in the inverse order : you must execute the statement before you can fetch data (that's obtained by executing it).
Basically, instead of using this :
// fetch, then execute ???
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
You should use that :
// Execute, **then** fetch
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Looks like you are fetching before executing?
Related
I use PDO on my local computer to connect to MS SQL server to use prepare statements. The driver is installed properly and can connect to database. Here's the code:
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
print $num;
From SSMS the query returns as it should, but nothing from the code as it prints -1 as the result of $num. If i change the query to SELECT ##VERSION it prints the version properly but not my query. My query is right from SSMS and PDO can connect to server but can't figure out where the problem is it's so frustrating please help.
can you try :
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
$num = count($rows);
print $num;
// To print results :
foreach ($rows as $row) {
echo $row["ClientID"] . "<br/>";
}
try {
$conn = new PDO('mysql:host=localhost;dbname=dbtable', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT * FROM table WHERE name = ' . $conn->quote($name).' AND id = '. $conn->quote($id));
$data->execute();
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo "ID : ".$row['id'].'</br>';
echo "Name : ".$row['name'].'</br>';
echo "Name : ".$row['header'].'</br>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
The above works for one parameter (name) but when i use AND operator it shows no results. URL is as given below.
http://www.mywebsite.com/page.php?id=2&name=xyz
As mentioned in the documentation, you're strongly advised to use parametrized queries, like so:
$data = $conn->prepare('SELECT * FROM table WHERE name = :name AND id = :id');
$data->bindParam(":name", $name);
$data->bindParam(":id", $id);
If this still does not work, I would suggest running a similar query directly against your database, through either phpMyAdmin or the MySQL Workbench, to verify that the query actually returns anything.
$data = $conn->prepare("SELECT * FROM table WHERE name = '$name' AND id <> '$id' ");
The above code worked for me.
I'm getting the error:
ERROR: SQLSTATE[HY000]: General error: 2053
I have no idea why this is happening because the code works fine and the database is updated, but it still returns this error.
Here's my code:
<?php
header("Content-Type: application/json; charset=UTF-8");
require 'UHCauth.php';
try {
$conn = new PDO("mysql:host=$mysql_serv;dbname=$mysql_db", $mysql_user, $mysql_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(isset($_GET['d6518e47'])) {
$USERNAME = $_GET['d6518e47'];
$stmt = $conn->prepare(
"UPDATE $mysql_table
SET KILLS = KILLS+1 WHERE USERNAME = :USERNAME"
);
$stmt->execute(array('USERNAME' => $USERNAME));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
} else {
$stmt = $conn->prepare(
"SELECT * FROM $mysql_table
ORDER BY
McVersion DESC,
ModVersion DESC
LIMIT 1"
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
$row = $stmt->fetch(PDO::FETCH_ASSOC); is the line that will cause your error.
Why?
Because there's nothing to fetch - in array - after an update
Remember that
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
So, no result set ... no party
If you want to know exit status of your command, just use the return value of execute() function
$rv = $stmt->execute(array('USERNAME' => $USERNAME));
I am using the following code for reading a String from a mysql function:
<?php
print_r($_POST);
try {
$dbh = new PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
print $value ;
//print $dbh ;
$stmt = $dbh->prepare("CALL check_user_exists(?)");
$stmt->bindParam(1, $value, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
echo "PDO connection object created";
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
This is not reading the returned value , however if I read the value usimg mysql* like :
<?php
$dbhost='myhost';
$dbuser='mydb';
$dbpassword='mypass';
$db='mydb';
$con=mysql_connect($dbhost, $dbuser, $dbpassword) or die("Could not connect: " . mysql_error()); ;
mysql_select_db($db,$con);
$qry_str = "select check_user_exists('chadhass#hotmail.com')";
$rset = mysql_query($qry_str) or exit(mysql_error());
$row = mysql_fetch_assoc($rset);
mysql_close($con);
foreach($row as $k=>$v)
{
print $k.'=>'.$v;
}
?>
This returns correctly . ANy idea wha am I missing ?
function :
CREATE
FUNCTION `check_user_exists`(in_email
VARCHAR(100)) RETURNS varchar(1) CHARSET utf8
READS SQL DATA
BEGIN
DECLARE vcount INT;
DECLARE vcount1 INT;
SELECT COUNT(*) INTO vcount FROM USERS
WHERE USEREMAIL=in_email;
IF vcount=1 then
SELECT COUNT(*) INTO vcount1 FROM USERS
WHERE USEREMAIL=in_email and isactive=1;
if vcount1=1 then
return('1');
else
return('0');
end if;
ELSE
RETURN('2');
END IF;
END
code that worked for PDO ::
<?php
//print_r($_POST);
try {
$dbh = new PDO(PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
$result = $dbh->prepare("select check_user_exists(?) as retval");
$result->bindParam(1, $value, PDO::PARAM_STR, 2);
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
$result->execute();
$obj = $result->fetch();
print($obj->retval);
echo "PDO connection object created";
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
The reason is, you aren't fetching the results from the query.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
I am using SQLite for one of my application I’ve a condition that I first run a query and if it returns result then I retrieve its data but if the first query doesn’t return anything I want to run another query that ll just select any random row from the database and ll return the results.
I’ve devised following code its working fine if it matches the data in the first case but this is not working for the second case.
$sql_query = "SELECT (select count(*)) as count,* FROM item WHERE combo LIKE '%" . $ans_combo . "%' LIMIT 1;";
$sql_query_bu = "SELECT * FROM item ORDER BY RANDOM() LIMIT 1;";
ini_set('display_errors', true);
error_reporting(E_ALL);
try {
$dbh = new PDO("sqlite:src/appdb.s3db");
$dbh -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $dbh -> prepare($sql_query);
$stmt -> execute();
foreach ($stmt as $row) {
if ($row['count'] != '1') {
echo $sql_query_bu . "<br/>";
$stmt = $dbh -> prepare($sql_query_bu);
$stmt -> execute();
foreach ($stmt as $row) {
echo $row['name'], " ", $row['name'], " ", $row['name'], "\n";
}
}
echo "Count: " . $row['count'];
echo $row['name'], " ", $row['name'], " ", $row['name'], "\n";
}
} catch(Exception $ex) {
var_dump($ex);
}
unset($dbh);
unset($stmt);
Kindly guide me through this.
Thank you.
If there is no record that matches the WHERE clause the first call to fetch() will return FALSE. In that case you can simply send the ORDER BY RANDOM()* query and fetch the first record.
self-contained example:
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);
$stmt = $pdo->prepare('SELECT * FROM soFoo WHERE combo=? LIMIT 1');
$stmt->execute( array('comboF') ) ;
$row = $stmt->fetch();
$stmt = null;
if ( !$row ) {
$row = $pdo->query('SELECT * FROM soFoo ORDER BY RANDOM() LIMIT 1')->fetch();
}
var_dump($row);
function setup($pdo) {
$pdo->exec('
CREATE TABLE soFoo (
combo TEXT,
x TEXT
)
');
$stmt = $pdo->prepare('INSERT INTO soFoo (combo,x) VALUES (?,?)');
$stmt->execute( array('comboA','A') );
$stmt->execute( array('comboB','B') );
$stmt->execute( array('comboC','C') );
$stmt->execute( array('comboD','D') );
}
(*) ORDER BY RANDOM() is e.g. in MySQL rather costly. I doubt that SQLite has a special routine for this case. Better search for a good alternative for ORDER BY RANDOM()