prepared statement PDO Probably small mistake - php

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);

Related

PDO return success but no data is updated on database

when i try to update a row with PDO function it returned success and when i check database there was no data updated
so i followed this question PDOStatement::execute() returns true but the data is not updated which has answers already but didn't work here is what i did
Below is code i tried
<?php
$Fuid = '105199239598939142575';
sendOT($Fuid);
echo '<br>Below is var_dump() Rsult<br>';
check($Fuid);
function sendOT($Fuid) {
try {
$phone = '6381211774';
$otp = '1234';
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code AND phone=:phone WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->bindParam(':veri_code', $otp, PDO::PARAM_STR);
$stmt2->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt2->execute();
echo 'Updated succeeded';
} catch (Exception $e) {
echo $e;
}
}
function check($Fuid) {
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("SELECT * FROM members WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->execute();
$unr = $stmt2->fetch(PDO::FETCH_ASSOC);
var_dump($unr);
}
?>
Output
as per the answer in this question PDOStatement::execute() returns true but the data is not updated may be there is no row with WHERE so i tried with the same WHERE with SELECT query and it showed result.
WHY is my UPDATE query doesn't update in database?
After many tries i managed to update with this query.
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code, phone=:phone WHERE Fuid=:Fuid");
it worked after removing AND from query using como , in update queries.

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

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

PHP PDO Simple insert does not work

I am converting all of my query's to PDO, and i'm new to it.
It's properly a very stupid question but why does the following code not work?
try {
$conn = new PDO('mysql:host=localhost;dbname=ddd', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_SESSION['id'];
$name = $_POST['name'];
$stmt = $pdo->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
$stmt->execute(array(
':id'=>$id,
':name'=>$name
));
Thanks.
Your connection variable is $conn and you are preparing your PDO Statement using $pdo->prepare.
Change to $conn->prepare()
$stmt = $conn->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
You're initializing a variable for your database connection called $conn yet later call $pdo that's not mentioned anywhere. That's the first thing I'd start with.

How to avoid mysql injections using PDO

How can I avoid mysql injections? This is the PHP file I have right now
<?php
include 'config.php';
$Name = $_GET['Name'] ;
$sql = "Select * from tables where names =\"$Name\"";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->query('SET CHARACTER SET utf8');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$names = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($names) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
When I put $stmt = $dbh->query($sql); $stmt->execute(array(':name' => $name)); to the code it doesn't work. So how should I do it?
Read about pdo prepared statements
Here is an example
$stmt = $dbh->prepare("SELECT * FROM tables WHERE names = :name");
$stmt->execute(array(':name' => $name));

Categories