What is wrong with my PDO prepared statement? [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 months ago.
Obviously, I am preparing the statement wrong, but I am not certain what I am doing wrong.
These 2 code segments are identical, except for the second line.
This fails:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
This hard-coded test works:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = 'me#example.com' OR `Users`.`Temp_EMail` = 'me#example.com'");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
What am I doing wrong?
Thanks!
UPDATE: Solved!
The exact issue is still unknown, but seems to be related to the 'excessive naming' suggested by user 'Your Common Sense' in the comments below.
This works just fine:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM Users WHERE EMail=:email OR Temp_EMail=:temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
Thanks to everyone. I learned lots AND resolved the issue.
Message to Your Common Sense; If you form your comment as an 'Answer', then I can accept it.

It's hard to answer on sight.
Your code seems okay to me. So, debugging seems the only way.
What am I doing wrong?
Always ask this question from your PDO.
Every time you're connecting to PDO, do it this way (also make sure you can see errors, either on-screen or logged):
error_reporting(E_ALL);
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = 'mysql:host=localhost;dbname=' . $DB_Database;
$dbh = new PDO($dsn, $DB_UserName, $DB_Password, $opt);
if there is an error - you'll be notified.
If there isn't - check typo-like problems.

Just a quick try - Do you get it right with these two lines ?
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => 'me#example.com', ':temp_email' => 'me#example.com'));
in other words... Did you set your $email variable ?

try this
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->bindParam(':email', $email, PDO::PARAM_STR);
$sth->bindParam(':temp_email', $email, PDO::PARAM_STR);
$sth->execute();
$res = $sth->fetch(PDO::FETCH_ASSOC);
$dbh = null;

Related

prepared statement PDO Probably small mistake

im rewriting all my database queries so that they are prepared and with PDO (before I used mysqli) so that they are save against sql injections. Now I'm new to PDO so its probably a small mistake that I dont see, so I hope u guys can help me out because this code doesnt work.
<?php
function getUserBalance($steamid)
{
include 'settings.php';
$conn = new PDO("mysql:host="$servername";dbname="$dbname"", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("SELECT balance FROM users WHERE steamid= :steamid");
$stmt = $conn->prepare($sql);
$stmt->bind_param(":steamid", $steamid, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
return $row['balance'];
}
}
$stmt->close();
?>
Okey so now I changed it to new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);, moved the $stmt->close(); within the function (oops) , and changed bind_param to bindParam, Thx guys its working now
<?php
include 'ChromePhp.php';
function getUserBalance($steamid)
{
include 'settings.php';
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT balance FROM users WHERE steamid= :steamid";
$stmt = $db->prepare($sql);
$stmt->bindParam(':steamid', $steamid, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
return $row['balance'];
}
$stmt->close();
}
?>
Change this line
$conn = new PDO("mysql:host="$servername";dbname="$dbname"", $username, $password);
to this
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

PHP PDO with Microsoft SQL Server: Prepare Statement issues?

I am fairly new to PDO. I am trying to run a query(Microsoft Sql Server). Eventually i am going to add more fields after WHERE.
$complex = 'Shipping';
$username= 'username';
$password = 'password';
try {
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query, array($complex));
$stmt->execute();
while($row = $stmt->fetch())
{
echo "$row\n";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I keep getting this error:
Fatal error: Call to a member function execute() on a non-object in
What am i doing wrong?
UPDATE
I tried this as well:
try {
$conn = new PDO('sqlsrv:Server=mzrefd39,1433;Database=ger_mapv', $username, $password);
$sth = $conn->prepare("SELECT AREA FROM TrimTable WHERE COMPLEX LIKE ?");
$sth->execute(array($complex));
$data = $sth->fetchAll();
print_r($data);
}
In my page i get Array( ). I am not getting any values?
You can use bindParam() before execute, Try this code
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query); // check $complex is removed from this line
$stmt->bindParam(1, $complex);
$stmt->execute();
Use bindParam(); for condition to execute query for conditions

PDO parameterized query code review, how safe am i?

I'm a PHP newbie that just starts to code. Before coding any further, I need to know if I already on the right path on making a secure web. So please review my code samples below.
PHP Version 5.4.34
Database Server version: 5.5.40-cll - MySQL Community Server (GPL)
on connection.php
//should I use utf8mb4 and set server connection collation to utf8mb4_general_ci?
//also on html, is including <meta charset="utf-8"> necessary?
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // enabled by default?
select query
$query = "SELECT * FROM tbname WHERE username = :username";
$params = array(':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
insert query
$query = "INSERT INTO log (
username,
email,
ip,
time
) VALUES (
:username,
:email,
:lastip,
:lastlog
)";
$params = array(
':username' => $_POST['username'],
':email' => $_POST['email'],
':lastip' => $_SERVER['REMOTE_ADDR'],
':lastlog' => time()
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
update query
$params = array(
':username' => $_SESSION['userdata']['username'],
':email' => $_POST['email'],
':age' => $_POST['age'],
':gender' => $_POST['gender']
);
$query = "UPDATE users SET
email = :email,
age = :age,
gender = :gender
where username = :username";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
How safe am i from SQL injection? Safe enough from 2nd order attack?
Totally safe. The PDO Statement prepares the query to avoid SQL injections. Even if they try, the prepare() function make the necessary changes before send to the database.

mysqli does not execute Select statement

I have the code bellow. When I use this code without the WHERE clause, all the users from the table are displayed, as expected. But when the WHERE clause is used, nothing is displayed.
What could be the cause and how can I fix it?
Thank you!
function requestUser($user) {
$DBHost = "localhost";
$DBUser = "dbUser";
$DBPass = "dbPass";
$DBName = "dbName";
$db = new mysqli($DBHost, $DBUser, $DBPass, $DBName);
if ($db -> connect_errno > 0) {
$lbOK = false;
}
else {
$lbOK = $db -> set_charset('utf8');
}
if ($lbOK) {
$id = NULL;
$user_name = NULL;
$user = htmlentities($user, ENT_QUOTES);
$lcSQL = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db -> prepare($lcSQL);
$ok = $stmt -> bind_param('s', $user);
$ok = $stmt -> execute();
$ok = $stmt -> bind_result($user_name);
while ($row = $stmt -> fetch()){
echo $user_name;
}
$stmt->close();
}
}
There are many major faults with your code, some of them can be responsible for the problem, and some not. But nevertheless, they all have to be corrected
Never connect co database inside of an application function. Connect somewhere in the bootstrap file, once, and use that single connection throughout all the application.
Do not use htmlentities with whatever database interactions. It may easily spoil the data
Always check for the the errors
Do not use mysqli, it is unusable. Use PDO instead.
$dsn = "mysql:host=DBHost;dbname=DBName;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,$DBUser, $DBPass, $opt);
function requestUser($user) {
global $db;
$sql = "SELECT `user_name` FROM `users` WHERE user_name=?";
$stmt = $db->prepare($sql);
$stmt->execute(array($user));
return $stmt->fetchColumn();
}
echo requestUser($user);
if it still doesn't work, verify it this way
$sql = "SELECT `user_name` FROM `users` WHERE user_name='$user'";
var_dump($sql);
and then try to run in console/phpmyadmin to find out what's wrong with your data/value

Prepared statement using PHP

I'm new to PHP .. I get stuck on how to transfer my sql statement to prepared statement .. The error message that I got is that you " can't connect " ..
My code is as the following
$connection = mysql_connect($host,$username,$password) or die ("can't connect");
$select_database = mysql_select_db($db_name);
$id = mysql_real_escape_string ($_GET ['id']);
$query = 'SELECT * from &tbl_name where id=?';
$stmt = $connection->prepare($query);
$stmt->bind_param("d", $id);
$stmt->execute();
$rows=mysql_fetch_array($stmt);
$stmt->close();
You have two problems actually.
The first, and relevant to your question, is on this line:
$connection = mysql_connect($host,$username,$password) or die ("can't connect");
You say you're receiving the error can't connect. This means that the host, username and/or password for your database connection is invalid. Check that the connection information is correct and you should be able to fix the issue.
The second is that you're connecting to your database with mysql_ functions and then trying to use mysqli_ binding/executing functions. You can't mix and match.
Because you're attempting to bind/execute with OOP style, here's a re-coded sample that should help out:
$connection = new mysqli($host, $username, $password);
if ($connection->connect_error) {
die("can't connect");
}
$query = 'SELECT * from tbl_name where id=?';
$stmt = $connecton->prepare($query);
$stmt->bind_param("d", $id);
$results = $stmt->execute();
$rows = $results->fetch_array();
$stmt->close();
You cannot do prepared statements with the legacy mysql_* set of functions. You need to use PDO or MySQLi:
$dbh = new PDO("mysql:dbname=testdb;host=127.0.0.1", "username", "password");
$query = "SELECT * FROM myTable WHERE id=?";
$stmt = $dbh->prepare($query);
$stmt->execute(array($my_id));
$result = $stmt->fetchAll();
The "can't connect" you have comes from the die() function which will stop execution of your script if mysql_connect fails. This means that your code doesn't succeed creating a connection, check your $host, $username and $password parameters. If your host is remote, make sure that you have the rights to connect to it.
As pce stated, you also have a typo in $connecton which should be $connection
try
1.Define the Database const for later use in your project; (this code should only be executed once)
define( "DBN","foo");//where foo is the database name
define( "DB_USERNAME", "rootuser" ); //generally root
define( "DB_PASSWORD", "my_very_hard_password" ); //be more creative
define( "DB_DSN", "mysql:host=localhost;dbname=".DBN );
...
2.Create PDO Object and execute
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * from &tbl_name where id=:id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $obj->id, PDO::PARAM_INT );
// or $st->bindValue( ":id", 5, PDO::PARAM_INT );
$st->execute();
return $st->fetchAll();

Categories