I have a couple of questions all pertaining to the same problem. I'm trying to update some of my MySQL connections/commands to PDO in order to mitigate SQL injections. I'm trying to convert this code:
$ulog = $_POST['driver'];
$_SESSION['user_id'] = $ulog;
$tablename_cc = "cc_".$ulog;
$tablename_db = "db_".$ulog;
$tablename_misc = "misc_".$ulog;
$tablename_cash = "cash_".$ulog;
$sql_cc = "SELECT * FROM " .$tablename_cc;
$sql_db = "SELECT * FROM " .$tablename_db;
$sql_misc = "SELECT * FROM " .$tablename_misc;
$sql_cash = "SELECT * FROM " .$tablename_cash;
$result_cc = mysql_query($sql_cc);
$result_db = mysql_query($sql_db);
$result_misc = mysql_query($sql_misc);
$result_cash = mysql_query($sql_cash);
To the following code:
$tables = array($tablename_cc, $tablename_db, $tablename_misc, $tablename_cash);
$A = count($tables);
$result = array();
try {
$STH = $DBH->prepare('SELECT * FROM :table');
$i = 0;
while($i < $A) {
$STH->bindParam(':table', $tables[$i]);
$STH->execute();
$result[$i] = $STH->fetchAll();
$i++;
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
However, I keep getting a syntax error. The error goes away if I try it in the following way, but this way is not very useful to me because it does not avoid SQL injections.
try {
$i = 0;
while($i < $A) {
$STH = $DBH->query('SELECT * FROM ' .$tables[$i]);
$result[$i] = $STH->fetchAll();
$i++;
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
Although this last method works, from my understanding it does not help with mitigating SQL injection. And a secondary issue I'm running across is that sometimes these tables will not exist and my workaround for these issues in the old method was to do a small check:
$result_cc = mysql_query($sql_cc);
if(mysql_num_rows($result_cc) != 0){}
However, this intermediate step seems to be gone in PDO, so I still need to figure out how to check for this.
Related
I need help with converting this SQL to Prepared Statement. This is for my search bar. I hope I'll be able to receive some help as I am a beginner in this.
This is my SQL
$conn = mysqli_connect('localhost','root','','my_db');
$mysql = "SELECT * FROM catetable";
$bike_list = mysqli_query($conn,$mysql);
$catesql = "SELECT catename FROM catetable";
$cate_list = mysqli_query($conn,$catesql);
And this is what I would like to change to Prepared Statement
if (isset($_GET['search']))
{
$search = $_GET['search'];
$searchlist = array();
$lowersearchlist = array();
$i = 0;
while ($one_cate = mysqli_fetch_assoc($cate_list))
{
$searchlist[$i] = $one_cate['catename'];
$lowersearchlist[$i] = strtolower($one_cate['catename']);
$i++;
}
if (in_array($search,$searchlist) || in_array($search,$lowersearchlist))
{
header("Location:feature.php");
}
else
{
header("Location:index.php?error=true");
}
}
Write a query that matches the parameter in the WHERE clause. MySQL normally defaults to case-insensitive comparisons, so you don't need to fetch all the rows to compare them exactly and case-insensitively.
if (isset($_GET['search'])) {
$stmt = $conn->prepare("SELECT COUNT(*) AS c FROM yourTable WHERE catename = ?");
$stmt->bind_param("s", $_GET['search']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['c'] > 0) {
header("Location: feature.php");
} else {
header("Location: index.php?error=true";
}
}
I already create an apps that contain ListView. I uses PHP to connect between android and database. FOr now, I use MySQLi and it works. But when I convert to PDO, the data not displayed. I uses 'Log.d' to trace what the data got. Below is the result:
MySQLi (No error) - {"data":[{"report_id":19,"task_name":"ngantuk","badgeid":"12345","report_date":"04 Dec 2019",.......
PDO (not log show data)
Now, below is current code for MySQLi and PDO
MySQLi
<?php
require_once 'config.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = '$badgeid' AND report_status = 'Pending';");
$stmt->execute();
$stmt->bind_result($report_id, $task_name, $badgeid, $report_date, $photo_before, $photo_after, $report_status);
$task = array();
while($stmt->fetch()){
$temp = array();
$temp['report_id'] = $report_id;
$temp['task_name'] = $task_name;
$temp['badgeid'] = $badgeid;
$booked = strtotime($report_date);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $report_date;
$temp['photo_before'] = $photo_before;
$temp['photo_after'] = $photo_after;
$temp['report_status'] = $report_status;
array_push($task, $temp);
}
$response = array();
$response["data"] = $task;
echo json_encode($response);
?>
PDO
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$task = array();
while ($result) {
$temp = array();
$temp["data"] = $task;
array_push($task, $temp);
}
$response = array();
$response["data"] = $result;
echo json_encode($response);
?>
Does anyone know what is problem with my PDO code?
The mysqli code and PDO code are not the same. I copied the code from the mysqli version to the PDO version.
PDOStatement::fetch() gets one row at a time. When you take the results from fetch and put it into the condition of a while loop, you are creating an infinite loop which will eventually run out of memory.
require_once 'configPDO.php';
$badgeid = $_GET["badgeid"] ?? "";
$stmt = $conn->prepare("SELECT report_id, task_name, badgeid, report_date, photo_before, photo_after, report_status FROM report WHERE badgeid = :badgeid AND report_status = 'Pending'");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->execute();
$task = [];
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$temp = [];
$temp['report_id'] = $result['report_id'];
$temp['task_name'] = $result['task_name'];
$temp['badgeid'] = $result['badgeid'];
$booked = strtotime($result['report_date']);
$report_date = date("d M Y", $booked);
$temp['report_date'] = $result['report_date'];
$temp['photo_before'] = $result['photo_before'];
$temp['photo_after'] = $result['photo_after'];
$temp['report_status'] = $result['report_status'];
$task[] = $temp;
}
$response = [];
$response["data"] = $task;
echo json_encode($response);
i'm having problems with translating simple sql queries to pdo sql queries but my code doesn't seems to run...
I had something like this in simple sql:
Sql(query)
If(row == variable){
Sql(query)
If(row>variable){
Sql(query)
}
}
This worked in simple sql queries but trying to use pdo doesn't work... I don't know why... Y have to make several pdo for every query? I'm using only one dbh pdo...
require 'dbdata.php';
$fb = $_POST["FB"];
$gg = $_POST["GG"];
$points = $_POST["Points"];
$lb = $_POST["leaderboard"];
$ID;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if(!empty($fb)){
$FBQ = $DBH->prepare("SELECT ID FROM Usuarios WHERE FbID='$fb'");
$count = $FBQ->rowCount();
$FBQ->setFetchMode(PDO::FETCH_ASSOC);
while($row = $FBQ->fetch()) {
$ID = $row['ID'];}
if($count > 0){
$LBQ = $DBH->prepare("SELECT * FROM $leaderboard WHERE UserID = $ID");
$countlb = $LBQ->rowCount();
$LBQ->setFetchMode(PDO::FETCH_ASSOC);
if($countlb >0){
while($row = $LBQ->fetch()) {
if($row['Puntuacion'] < $points){
$LBQS = $DBH->prepare("UPDATE $leaderboard SET Puntuacion = $points WHERE UserID = $ID");
$LBQS -> execute();
echo "Actualizado Record";
}
}
}
}
}
}
Any help is apreciated, thanks in advance!
I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}
I am trying to update a file OPPSHEDT with a priority and reason code. It seems the code gets stuck in the foreach loop. It gets to SQL with the Count I get the echo of the selstring on my browser then I do not get the echo of $Count and the update is not done. I'm not quite sure if I'm not connecting and doing the actual SQL on the Count or not. Is there anyway to tell what is going on here?
<?php
require_once ('C:/wamp/db/login.php');
// Try to connect to database
try
{
$db = new PDO($db_hostname, $db_user, $db_pass);
}
catch (PDOExcepton $e)
{
echo $e->getMessage();
exit();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (is_array($_POST['line']))
{
$ohord = $_POST['shedord'];
$ohbord = $_POST['shedbord'];
$date1 = $_POST['sheddat'];
$type = $_POST['shedtyp'];
$prty1 = $_POST['shedpty'];
$resn1 = $_POST['shedrsn'];
foreach($_POST['line'] as $line_no)
{
$type1 = $type[$line_no];
$type2 = substr($type1, 0, 1);
$selstring = "Select Count(*) From LPCUSTTST.OPPSHEDT where sheddat = '$date1[$line_no]' and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring;
$s = $db->prepare("$selstring");
$s->execute();
echo $Count;
if($Count > 0)
{
// Update data into detail
$selstring1 = "UPDATE LPCUSTTST.OPPSHEDT SET SHEDPTY = '$prty1[$line_no]', SHEDRSN = '$resn1[$line_no]' where sheddat = $date1[$line_no] and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring1;
$s = $db->prepare("$selstring1");
$s->execute();
}
}
}
?>
Thank You
Your first SQL statement contains date1[$line_no] while your second contains $date1[$line_no]. You can make things much easier (and safer) by using parameterized queries instead.
Edit: You modified your post to include the missing dollar sign but my suggestion to use parameterized queries still stands.
$selstring = 'SELECT COUNT(*) as total
FROM LPCUSTTST.OPPSHEDT
WHERE sheddat = :sheddat
AND shedtyp = :shedtyp
AND shedord = :shedord
AND shedbord = :shedbord';
$stm = $db->prepare($selstring);
$stm->execute(
array(
'sheddat' => $date1[$line_no],
'shedtyp' => $type2,
'shedord' => $ohord[$line_no],
'shedbord' => $ohbord[$line_no]
)
);
I do not get the echo of $Count and the update is not done
In your code you do echo $Count; but $Count is never defined. You need to fetch the value (I added total to the above SQL):
$row = $stm->fetch(PDO::FETCH_ASSOC);
$count = $row['total'];