cant update mysql data with json - php

look this my code for update data in mysql
$id = intval($_REQUEST['id']);
$user = htmlspecialchars($_REQUEST['username']);
$pass = htmlspecialchars($_REQUEST['password']);
include 'koneksi.php';
$sql = "update account set username='$user',password='$pass',where user_id=$id";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array(
'user_id' => $id,
'username' => $user,
'password' => $pass
));
} else {
echo json_encode(array('errorMsg'=>'Some errors occured.'));
}
;
and the result in some errors occured
how solved this :D

You have not posted any errors, so I am going to go based on what I know.
on this line:
$result = #mysql_query($sql);
You should remove the # which will supress your warnings, because you have an error in your mysql query.
Your query will evaluate to this
update account set username='matt', password='my_pass', where user_id=100
The issue is the comma after the password, there should not be one before your WHERE.

Related

What could cause a PHP insert into a MYSQL database to wrongly insert data from another user into a row?

A student of mine was saving her score for a learning game to a MySQL database but somehow a different person's name ended up being stored in her database row. How is this possible? Here is the PHP for the insert.
// Get Configuration file
require "configenzymatic.php";
// Connect to your server
$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
///////////////////////////////////////////////////////
// Status Checker
///////////////////////////////////////////////////////
if ($_GET["status"]) {
echo "online";
exit;
}
///////////////////////////////////////////////////////
// Upload new score
///////////////////////////////////////////////////////
//set POST data as data to be checked and updated
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$level1right = $_POST['level1right'];
$level1wrong = $_POST['level1wrong'];
$level2right = $_POST['level2right'];
$level2wrong = $_POST['level2wrong'];
$level3right = $_POST['level3right'];
$level3wrong = $_POST['level3wrong'];
$level4right = $_POST['level4right'];
$level4wrong = $_POST['level4wrong'];
// check for email and set hash variable
$stm = $dbh->prepare("SELECT * FROM $tname WHERE email=?");
$stm->bindValue(1, $email, PDO::PARAM_STR);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$hashes = array($row['hash']);
$hash = $row['hash'];
$id = $row['id'];
foreach ($hashes as $hash) {
// If hash matches password, then...
if (password_verify($password, $hash)) {
// Everything is cool -- Insert the data into the database (update)
$stmt = $dbh->prepare("
UPDATE $tname
SET firstname = :firstname
, lastname = :lastname
, hash = :hash
, level1right = :level1right
, level1wrong = :level1wrong
, level2right = :level2right
, level2wrong = :level2wrong
, level3right = :level3right
, level3wrong = :level3wrong
, level4right = :level4right
, level4wrong = :level4wrong
WHERE email = :email
AND id = :id");
$stmt->execute(array($firstname, $lastname, $hash, $level1right, $level1wrong, $level2right, $level2wrong, $level3right, $level3wrong, $level4right, $level4wrong, $email, $id));
$affected_rows = $stmt->rowCount();
// check if row inserted
/* Return number of rows that were updated */
$count = $stmt->rowCount();
echo "$count";
}
}
}
The student inputted her name but someone else's name got inserted. I am totally baffled by this. Does anyone have any idea how this could occur? The person whose name was inserted in place of my student's added data at 12:30:44 today and my student added her data at 13:44:15. How did this data get mixed?
I'm not certain why you had your update wrapped in multiple loops, but it's entirely possible that users with the same password hash could exist, and (I think) would explain the behaviour you're seeing.
You are, presumably, looking to update the single user with the email and password submitted in the form? I assume you also have constraints on your table to ensure that email addresses are unique. So, you're grabbing the single user that matches that email, and checking their password. If it matches, update the single record with the same database ID. No loops!
// get password hash
$stm = $dbh->prepare("SELECT id, hash FROM $tname WHERE email=?");
$stm->execute([$_POST["email"]]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
$hash = $row['hash'];
$id = $row['id'];
if (!password_verify($_POST["password"], $hash)) {
// verification failed, do something to present an error to the user
die();
}
$stmt = $dbh->prepare(
"UPDATE $tname
SET firstname=:firstname, lastname=:lastname,
level1right=:level1right, level1wrong=:level1wrong,
level2right=:level2right, level2wrong=:level2wrong,
level3right=:level3right, level3wrong=:level3wrong,
level4right=:level4right, level4wrong=:level4wrong
WHERE id=:id"
);
$stmt->execute([
":firstname" => $_POST["firstname"],
":lastname" => $_POST["lastname"],
":level1right" => $_POST["level1right"],
":level1wrong" => $_POST["level1wrong"],
":level2right" => $_POST["level2right"],
":level2wrong" => $_POST["level2wrong"],
":level3right" => $_POST["level3right"],
":level3wrong" => $_POST["level3wrong"],
":level4right" => $_POST["level4right"],
":level4wrong" => $_POST["level4wrong"],
":id" => $id
]);
$count = $stmt->rowCount();
echo "$count";
Also note that using named parameters in PDO requires the use of an associative array. Not sure how your original code would update anything at all without that.

Updating database using dropdown without using a submit button

I'm trying to update the table status value whenever I make a selection from the dropdown list.
The problem is I'm having a syntax error on my update query. I've read stuff about syntax error and I can't quite understand it. I think I'm gonna need a more specific help. Here's what I've done:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "companydb";
try
{
$conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["status"]))
{
$query = "UPDATE tickets SET status = '$status' WHERE id = $id";
$statement = $conn->prepare($query);
$statement->execute(array('status' => $_POST["status"]));
$count = $statement->rowCount();
if($count > 0)
{
echo "Data Inserted Successfully..!";
}
else
{
echo "Data Insertion Failed";
}
}
else
{
echo "unknown index: 'status'";
}
}
catch(PDOException $error)
{
echo $error->getMessage();
}
?>
And here's my table schema:
You are not performing prepared statements properly. You need to add the placeholder in the query and not the variables. The variables should be added in the execute() line.
$query = "UPDATE tickets SET `status` = :status WHERE `id` = :id";
$statement = $conn->prepare($query);
$statement->execute(array(':status' => $_POST["status"],':id' => $id));
Also FYI, $id is undefined.
Try Changing this:
$query = "UPDATE tickets SET status = $status WHERE id = $id";

Please check MySQL query

I'm trying to fetch data using MySQLi Query.
Please check my SQL Query, i'm getting error on the If condition.
i add error which is beside
if condition
when it is getting displayed into console
<?php
$id = $_GET['id'];
include("../include/connection_string.php");
$sql = mysqli_query($db, "SELECT pages, main_id FROM dhms_index_table where main_id='"+$id+"'");
if(mysqli_num_rows($sql)){ // Showing error here " Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result"
$data = array();
while($row = mysqli_fetch_array($sql)){
$data[] = array(
'pages' => $row['pages'],
'main_ID' => $row['main_id']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
connections_string.php
$server = 'localhost';
$username ="root";
$passwd ='';
$Dbase = 'og_dhms';
$db = #mysqli_connect($server,$username,$passwd)
or die("Could not connect database");
#mysqli_select_db($db, $Dbase)
or die("Could not select database");
This line
main_id='"+$id+"'
is using + signs rather than dots to concatenate. That is the JS/C method to do that. Maybe you are from that type of background and thought you could use it in PHP; you can't.
so...
main_id='".$id."'
Also make sure you have a value for $id = $_GET['id'];.
Error reporting will tell you if it is or not.
If the GET array is an integer (which I am pretty sure it stands to be), you'd be best to use (int) for it.
$id = (int)$_GET['id'];
and checking if it's set / not empty.
I.e.:
if(isset($_GET['id'])){
$id = (int)$_GET['id'];
}
or
if(!empty($_GET['id'])){
$id = (int)$_GET['id'];
}
Your issue was most likely caused by a query syntax error here:
main_id='"+$id+"'
Changing that to this, should solve the issue:
main_id='".$id."'
But you should not use pure unfiltered user input in your sql statements.
I would do something like this:
<?php
$id = $_GET['id'];
include("../include/connection_string.php");
if($stmt = mysqli_prepare($db, "SELECT pages, main_id FROM dhms_index_table WHERE main_id = ?")) {
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $pages, $main_id);
$data = array();
while(mysqli_stmt_fetch($stmt)) {
$data[] = array(
'pages' => $pages,
'main_ID' => $main_id
);
}
header('Content-type: application/json');
echo json_encode($data);
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
?>
Always make sure to use prepared statements when you are including user input on statements to avoid SQL Injection.
Read more about it here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I hope it helped.

PDO query returns nothing

I have a problem with my query, it returns nothing.
if($champ == "type_id")
{
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
while($row = $request->fetch())
{
$bdd1 = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request1 = $bdd1->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
}
I'm getting variables from ajax request (JQUERY) and i initialize them before, i avoid you the code.
Other requests on the page works.
I have currently no way to see if somethings got wrong, due to ajax call. (No php orange boxes / pdo message)
I tried to solve to problems, and i discovered that we go into the if.
I deleted the first query which contains the while, i replaced $row['id'] by a value, and i worked.
Since the beginning, i keep copying and pasting the connection to my database so no problem.
So my problem is here:
$request = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
while($row = $request->fetch())
I don't see what i've done wrong...
$request = $bdd->prepare('SELECT * FROM type_commercant');
$request->execute();
while($row = $request->fetch())
This works, so i tried this:
$request = $bdd->prepare('SELECT * FROM type_commercant');
$request->execute();
while($row = $request->fetch())
{
if($row['type'] == $old)
{
$request1 = $bdd->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
}
We don't go in the condition if($row['type'] == $old), but i delete this condition, and when i replace with something like this:
while($row = $request->fetch())
{
$request1 = $bdd->prepare('UPDATE commercant SET adresse=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
}
It works... i checked $row['type'], $row['id'], $old in array(':type_id' => $row['id'], all variable got the string attented. So what's the problem?
Thanks in advance !
Hmm, how to say that...
I was updating the data with the old data i explain myself:
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
$request = $bdd->prepare('SELECT id FROM type_commercant WHERE type=:old');
$request->execute(array(':old' => $old));
was getting the old ID from type_commercant, and i was doing this:
$request1 = $bdd1->prepare('UPDATE commercant SET type_id=:type_id WHERE id=:id');
$request1->execute(array(':type_id' => $row['id'],':id' => $id));
So i replaced the old ID by... the old ID.
Sorry for that mistake, thanks anyway for reading me and trying so solve this problem :D
Try to call PDO::exec() for doing UPDATE or DELETE .
$bdd = new PDO("mysql:dbname=maruecondi_db;host=localhost","root","");
if($champ == "type_id")
{
$stmt = $bdd->prepare('SELECT * FROM type_commercant WHERE type=:old');
$stmt->execute(array(':old' => $old));
$rows = $stmt->fetchAll();
// Uncomment this to know what you get
// var_dump($rows);
foreach ( $rows as $row ) {
$bdd->exec(
"UPDATE commercant
SET type_id = " . $bdd->quote($row['id']) .
" WHERE id = " . $bdd->quote($id)
);
}
}
You can use this code for debugging.
var_dump( $bdd->errorInfo() );

PDO Querying database through sessions

I am trying to call data from my database to display on a users profile. I have the user session working correctly in the check user file. However the code below obviously isn; retrieving anything because it won't echo out in the echo statment i have in my HTML. Can someone please help???
require_once 'check.php';
if(isset($_GET['full_name'])){
$full_name = $_GET['full_name'];
$username = $_GET['username'];
$country = $_GET['country'];
$bio = $_GET['bio'];
$stmt = $dtb->prepare(" SELECT full_name=:full_name, username=:username, country=:country, bio=:bio FROM users WHERE id=:log_user_id AND username=:log_uname LIMIT 1");
$arr = array(
"full_name" => $full_name,
"username" => $username,
"bio" => $bio,
"country" => $country,
"log_user_id" => $log_user_id,
"log_uname" => $log_uname
);
ArrayBinder($stmt,$arr);
try{
$stmt->execute();
$dtb = null;
exit();
}
catch(PDOException $e){
echo $e->getMessage();
$dtb = null;
exit();
}
}
As it's absolutely IMPOSSIBLE to tell what are you trying to do from that mess you called "code" - so, just to give you an idea on the code you need to get user details from database based on id stored in a session:
$sql = "SELECT full_name,username,country,bio FROM users WHERE id=?";
$stmt = $dtb->prepare($sql);
$stmt->execute([$_SESSION['log_user_id']]);
$user = $stmt->fetch();
here in the $user array you should have name bio and stuff. Check session variable name

Categories