I'm fairly new to using PDO, and I'm attempting to migrate some of my websites from mysql_* to it.
I have formed the following:
if ($userData) {
$query = "SELECT * FROM table WHERE user_id = " . $db->quote($userData['id']);
$result = $db->query($query);
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = " . $db->quote($userData['id']) . "' AND `id` != '" . $row['id'];
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
if (!$row) {
$sql = "INSERT INTO tokens SET `user_id` = " . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute();
} else {
$sql = "UPDATE tokens SET `access_token` = " . $db->quote($token) . "' WHERE `id` = " . $row['id'] . "";
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
}
$userData is a Facebook API variable.
The snippet above looks fine to me, but when I run through it on a live website, the information isn't added to the database.
How would I fix this? Any assistance would be greatly appreciated.
You're missing a single quote
$sql = "INSERT INTO tokens SET `user_id` = <<HERE>>" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
should be:
$sql = "INSERT INTO tokens SET `user_id` = '" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
And on the update statement in the same place.
Ok I am going to tell you one thing, please use placeholders. I have also been through the same problem which you are in right now. mysql_ functions are deprecated and hence developers have to use PDO or mysqli_ functions.
Please check the code and see if it works
<?php
if($userData) {
$query = "SELECT * FROM table WHERE user_id = :user_id";
$result = $db->prepare($query);
$result->execute(array(':user_id' => $userData['id']));
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = :user_id AND `id` != :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':id' => $row['id']));
}
}
if(!$row) {
$sql = "INSERT INTO tokens SET `user_id` = :user_id, `name` = :name,`access_token` = :access_token ,`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':name' => $userData['name'], ':access_token' => $token));
} else {
$sql = "UPDATE tokens SET `access_token` = :access_token WHERE `id` = :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':access_token' => $token, ':id' => $row['id']));
}
}
}
?>
Related
I've tried the code below but it didn't work:
if (isset($_POST['ubah'])) {
$queryUpdate = mysqli_multi_query("INSERT INTO perbaikan SET id_perbaikan = '',idrusakbaik = '" . $id . "',komenrusak = '" . $_POST['komenrusak'] . "',tglbaik = '" . $tgl_sekarang . "'; UPDATE kerusakan SET status = '" . $_POST['status'] . "'WHERE id_kerusakan = '" . $id . "'");
if ($queryUpdate) {
echo "<script> alert('Data Berhasil Disimpan'); location.href='index.php?hal=master/perbaikan-mekanik/list' </script>";
exit;
}
}
There is no such thing as "two queries in one query". There are always two queries. and there is not a single reason to run them in one call. therefore just rewrite your query to two prepared statements
$sql = "INSERT INTO perbaikan SET id_perbaikan = '',idrusakbaik = ?,komenrusak = ?,tglbaik = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $id, $_POST['komenrusak'],$tgl_sekarang);
$stmt->execute();
$sql = "UPDATE kerusakan SET status = ? WHERE id_kerusakan = ?");
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $_POST['status'], $id);
$stmt->execute();
Can anybody help me to understand why my query update dosen't update my data in my database.
This my code php :
<?php
$code = $_GET['code'];
$n1= $_GET['n1'];
$n2= $_GET['n2'];
$n3 = $_GET['n3'];
try {
$connexion= new PDO('mysql:host=localhost;dbname=data','mydata','password');
$sql_update = "UPDATE data.check SET numb_1='".$n1."',numb_2='".$n2."','numb_3'='".n3."' WHERE 'code_product' =".$code;
$query = $connexion-> prepare($sql_update);
$query -> execute();
$data_update= $query -> fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "<br>" . $e->getMessage();
}
Thanks for any help.
1) Change
$sql_update = "UPDATE data.check SET numb_1='" . $n1 . "',numb_2='" . $n2 . "','numb_3'='" . n3 . "' WHERE 'code_product' =" . $code;
To
$sql_update = "UPDATE data.check SET numb_1='" . $n1 . "',numb_2='" . $n2 . "','numb_3'='" . $n3 . "' WHERE `code_product` =" . $code;
=> In n3 you forgot to add $. And, replace single quotes with backtick to enclose column name.
Updated Code
<?php
$code = $_GET['code'];
$n1 = $_GET['n1'];
$n2 = $_GET['n2'];
$n3 = $_GET['n3'];
try {
$connexion = new PDO('mysql:host=localhost;dbname=data', 'mydata', 'password');
$sql_update = $connexion->prepare("UPDATE `data`.`check` SET numb_1 = :numb_1 , numb_2 = :numb_2, numb_3 = :numb_3 WHERE `code_product` = :code_product");
$sql_update->execute(array(':numb_1' => $n1,':numb_2'=>$n2, ':numb_3'=>$n3,':code_product'=>$code));
$stmt = $connexion->prepare("SELECT * FROM `data`.`check` WHERE code_product=:code_product");
$stmt->execute(array(':code_product'=>$code));
$data_update= $stmt -> fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "<br>" . $e->getMessage();
}
?>
After your update execution you need to query again for fetching result like,
$sql_update = "UPDATE data.check SET numb_1='".$n1."',numb_2='".$n2."','numb_3'='".$n3."' WHERE 'code_product' =".$code;
$query = $connexion-> prepare($sql_update);
$query -> execute();
$query = $dbh->prepare("SELECT * FROM data.check");
$query->execute();
$data_update= $query -> fetchAll(PDO::FETCH_ASSOC);// now it will get records
I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.
I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.
use query for access the $current_rank this value want to access in different query but this value can not access any where in different query so how to access $current_rank......
$query = "select * from menu_master where menu_id =
$row_id and hotel_id='" . $_REQUEST['hotel_id'] . "'";
$result = mysql_query($query)."<br/>";
while($row=mysql_fetch_array($result))
{
$rank = $row['set_rank'];
}
$current_rank = $rank;
//echo $current_id = $row_id."<br/>";
//echo $new_rank =$_REQUEST['set_rank']."<br/>";
$sql = "select * from menu_master where set_rank = '$new_rank ' and hotel_id='".$_REQUEST['hotel_id']."'" ;
// echo $sql."<br/>";
$rs = mysql_query($sql)."<br/>";
while($row = mysql_fetch_array($rs))
{
$menu_id = $row['menu_id'];
$sql="update menu_master
set set_rank=$current_rank where menu_id= $menu_id and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
mysql_query($sql)."<br/>";
}
$sql="update menu_master set menu_name = '" . mysql_real_escape_string($_REQUEST['menu_name']) . "',
menu_name_ar = '" . mysql_real_escape_string($_REQUEST['menu_name_ar']) . "',
is_active = '" . $is_active . "',
set_rank = $new_rank where menu_id = '$current_id' and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
//exit;
mysql_query($sql);
Your current_rank seems to be an array. If you have single value in current_rank, then do not use while loop for it.
Just use $row=mysql_fetch_array($result);
$current_rank = $row['set_rank'];
Also you have commented out this line.
//echo $new_rank =$_REQUEST['set_rank']."";
So you have no value for $new_rank