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!
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";
}
}
My code working fine , but i got this error :
SQLSTATE[HY000]: General error
I searching on google and someone say that it's may SQLi
What is this ? And how can i fix that ?
thanks and sorry for my poor english
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Anti Brute Forced
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$users_username = $row["users_username"];
$users_password = $row["users_password"];
$users_wrong_password = $row["users_wrong_password"];
if ($users_wrong_password <= 3 && isset($_GET["username"],$_GET["password"]) && $_GET["username"] == $users_username && $_GET["password"] != $users_password){
$u = $users_wrong_password + 1;
$g = 0;
$g = $_GET['username'];
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute();
}
if ($_GET["username"] == $users_username && $users_wrong_password >= 4){
echo "Your Account Was Banned For 1 Hours";
die;
}
}
$g = $_GET['username'];
$stmt = $db_con->prepare("SELECT * FROM users where users_username = '$g'");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$ss = $row["users_wrong_password"];
}
if($ss <= 3){
$g = 0;
$g = $_GET['username'];
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = 0
WHERE users_username = '{$_GET['username']}'
");
$stmt->execute();
}
// Anti Brute Forced
[Solved]
Edit:
$g = $_GET['username'];
$p = $_GET['password'];
$stmt = $db_con->prepare("
SELECT * FROM users where users_username = '$g' and users_password = '$p'
");
I found this problem in a similar another way
"errorInfo":["HY000"]
How does "HY000" error happen?
It happens when you are updating, deleting or inserting data with PDO, and you try to fetch it's result.
The solution, just do not use fetch or fetchAll methods after executing an updating, deleting or inserting. Surely, it does not make sense to fetch it's result!
Example:
$stmt = $db_con->prepare("
UPDATE users SET name = 'Renato' WHERE ID = 0
");
$stmt->execute();
$stmt->fetch(PDO::FETCH_ASSOC); // The mistake is here, just remove this line
$stmt->fetchAll(PDO::FETCH_ASSOC); // It will cause troubles too, remove it
Solving the problem in a loop
The solution is changing the statement variable name inside loop, or fetch all before starting loop:
Solution: Changing variable name
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// ...
// This is another statment
$another_stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$another_stmt->execute();
}
Solution: Fetch all data from query before loop
$stmt = $db_con->prepare("
SELECT * FROM users
");
$stmt->execute();
// Everything is fetched here
$results = $stmt->fetchAll(PDO::FETCH_ASSOC)
foreach($results as $row){ // Another way to loop through results
$stmt = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute(); // Be happy with no troubles
}
I think there are multiple preparations of the same query.
Solution Get the query preparation out of the while.
code:
//... your code
$stmt1 = $db_con->prepare("
UPDATE users
SET users_wrong_password = $u
WHERE users.users_username = '$g'
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$users_username = $row["users_username"];
$users_password = $row["users_password"];
$users_wrong_password = $row["users_wrong_password"];
if ($users_wrong_password <= 3 && isset($_GET["username"],$_GET["password"]) && $_GET["username"] == $users_username && $_GET["password"] != $users_password){
$u = $users_wrong_password + 1;
$g = 0;
$g = $_GET['username'];
$stmt1->execute();
//...
}
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'];
I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.
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.