PHP Update doesn't Update - php

The query runs in mysql, there is no catch when you submit but the data doesn't update. Is there any advice on why this doesn't work or even how to debug this?
<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" )
{
// var_dump($_POST["first_name"]);
try
{
// this needs to be a lot more secure!
// read PDO manual
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = '$first_name' WHERE id = '52'");
$update = $db->query($sql);
}
catch ( Exception $e )
{
echo " Data could not be updated from the database.";
}
}
and the connection:
<?php
try
{
$db = new PDO("mysql:host=localhost;dbname=openstudios;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
// var_dump($db);
}
catch ( Exception $e )
{
echo "Could not connect to the database.";
exit;
}

You are not using prepare() (or query()) correctly here. prepare() is used to create a "prepared statement" that gets ran with execute() and query() is used to run an SQL query string.
DO NOT concatenate your $_POST values into your query string, that's how you open yourself up to SQL injections. You are ignoring the whole point of using prepared statements.
This is for MySQLi:
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = ? WHERE id = ?");
$sql->bind_param('sd', $first_name, $id);
$sql->execute();
See the docs: http://php.net/manual/en/mysqli.prepare.php
If you are using PDO, the syntax is a bit different
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = :first_name WHERE id = :id");
$sql->execute(array(
'first_name' => $first_name,
'id' => $id
));

For prepared statements you should be using something like this
$sql = $db->prepare('UPDATE exhibitors SET first_name = :first_name WHERE id = :id');
$sql->execute(array('first_name' => $first_name,'id' => 52));
In case you want to use query statement only, (which one should not, receptive to SQL injections)
$db->query("UPDATE exhibitors SET first_name = '$first_name' WHERE id = 52");

Related

Is it possible to parametarize query that has a concatenation variable?

As learning php and sql injections, I would like to parametize my queries for safe and secure website app. however, mine does not work I try to parametize my update and select my query but I didn't achieved the goal to make the program working.
The current output is throwing an error the ? is not found
As of now here is my code, am I missing something that does not work?
<?php
//connection
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
//Query No. 1
$qrQuery = "SELECT * FROM scratch_cards WHERE code='$qrid' ";
$qrQuery_run = mysqli_query($connection,$qrQuery);
//Query No. 2
$qrQuery2 = "UPDATE scratch_cards SET status = 'U' WHERE code='$qrid' ";
$qrQuery_run2 = mysqli_query($connection,$qrQuery2);
$qrQuery2->bind_param("s", $qrid);
$qrQuery2->execute();
while ($qrRow = mysqli_fetch_array($qrQuery_run)) {
$txtQrvalue = $qrRow['amount'];
$txtQrstatus = $qrRow['status'];
// QUERY TO UPDATE THE VALUE
// BIND AND PARAMETIZE MY QUERY
$qrQuery3 = $db->parepare("UPDATE shopusers SET ewallet = ewallet + " . (0+?) . " WHERE id = '?' ");
$qrQuery3->bind_param("ii", $txtQrvalue, $id);
$qrQuery3->execute();
//END
}
If I'm reading your question and code right, you can reduce this down to two queries using a JOIN instead, that way you can get rid of the SELECT statement. Use prepared statements for both.
I also specified your connection's charset to UTF-8 (which you should set for your PHP and HTML headers, and your database-tables too).
<?php
$connection = mysqli_connect("hostserver","username","");
$db = mysqli_select_db($connection, 'dbname');
$connection->set_charset("utf8");
if (isset($_POST['qrname'])) {
$qrid = $_POST['qrid'];
$sql = "UPDATE scratch_cards SET status = 'U' WHERE code=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
$sql = "UPDATE shopusers su
INNER JOIN scratch_cards sc
ON sc.qrid = su.code
SET su.ewallet = su.ewallet + sc.amount,
sc.status = 'U'
WHERE sc.code = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $qrid);
$stmt->execute();
$stmt->close();
}
we have the foll syntax in PDO bind param, where i have put your update query as an example and it works perfectly fine. Try searching for named parameter binding
<?php
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$mysqlConnection = new \PDO('mysql:host='.$host.';dbname='.$DB, $user, $pass);
$mysqlConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = 'update info set fname = fname + :fn where id = 1';
$stmt = $mysqlConnection->prepare($sql);
$stmt->bindValue(':fn', '100');
$stmt->execute();
echo $stmt->rowCount();
?>
Is this the query you wanted to run using mysqli bind params???
<?php
ini_set('display_errors', 1);
$user = 'root';
$pass = 'xxxx';
$DB = 'test';
$host = 'localhost';
$sql = 'update info set fname = fname + ? where id = 1';
$conn = new mysqli($host, $user, $pass, $DB);
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $val);
$val = 100;
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
exit;

Secure php and sql when selecting and inserting data

I have an app that takes data from MySQL database and also inserting data into it (the user is writing the data that is getting inserted) and honestly I am pretty new to php and don't know a lot about securing and sanitizing strings,
I want to make the php files more secure and I don't know what to look for in order of doing it, if someone can send a tutorial it will be great.
here is the select and insert codes
<?php
header('Content-Type: text/html; charset=utf-8');
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1],$row[2]));
}
$str = json_encode(array($response),JSON_UNESCAPED_UNICODE);
$str = clean($str);
echo $str;
mysqli_close($conn);
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^a-zA-Z0-9,×-×–, : . -]/', '', $string);
return preg_replace('/-+/', '-', $string);
}
?>
and the insert:
<?php
$db = "*********";
$username = "*********";
$password = "*******";
$host = "************";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
$name =$_POST["name"];
$publisher=$_POST["publisher"];
$date=$_POST["date"];
$sql_query = "insert into sample(name,publisher,date)
values('$name','$publisher','$date');";
if(mysqli_query($conn,$sql_query))
{
echo "data inserted";
}
else
{
echo "error";
}
?>
Use prepared statements any time possible:
$sql_query = "insert into sample(name,publisher,date) values(?,?,?);";
$stmt = mysqli_prepare($conn,$sql_query);
mysqli_stmt_bind_param( $stmt , "sss" , $name,$publisher,$date);
mysqli_stmt_execute($stmt);
And try to use the object style only, not the procedural of the mysqli extention.
You are mixing both here:
$conn = mysqli_connect($host,$username,$password,$db);//procedural style
$conn->set_charset('utf8');//oject style
You can use PDO. It's very simple to build safe SELECT and INSERT queries. Although, you must be careful on some commands such as ORDER BY.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename;charset=utf8', 'username', 'password');
$statement = $pdo->prepare("SELECT * FROM users WHERE firstname = :firstname AND lastname = :lastname");
$statement->execute(array(':firstname' => 'Max', ':lastname' => 'Mustermann'));
if( $statement->rowCount() > 0 ) {
$row = $statement->fetch();
echo "Hello " . $row['firstname'];
}
?>
Mysqli can be used too, but please check out mysqli_real_escape_string.

PDO delete from MySQL

I have a problem with a PDO code.
I try the code below.
$id = null;
if ( !empty($_GET['t_id'])) {
$id = $_REQUEST['t_id'];
}
$action = isset($_POST['_DELETE_']) ? $_POST['_DELETE_'] : "";
if ($action == 'do_not_delete') {
header("Location: index.php?action=DEL_ERROR");
}
if($action=='delete') {
$host = "localhost";
$db_name = "_notice";
$username = "root";
$password = "111";
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
$id = $_REQUEST['t_id'];
$query = "DELETE FROM topics WHERE topic_id = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $id);
$exc = $stmt->execute();
if($exc){
$con = null;
header("Location: index.php?action=DEL_OK");
}else{
$con = null;
header("Location: index.php?action=DEL_ERROR");
}}
Anything happens (dose not delete element from the database).
I have no errors on page; even when i use a try catch block, or page parameter like index.php?action=DELETE
You need to call $stmt->execute() after preparing the query and binding parameters.
Update:
You are checking the content of $_GET['t_id'] but always setting $id to $_REQUEST['t_id'], and everything will execute only if $_POST['_DELETE_'] contains delete.
Also, try to check the resulting query and parameters with $stmt->debugDumpParams() before executing and maybe replace your bindParam with $stmt->bindParam(1, $id, PDO::PARAM_INT).

mysqli_insert_id doesn't return anything

<?php
>here is database connection code
$connection = mysqli_connect($server_name,$user_name,$password,$database_name);
>the post variable comes from another page
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$birth_date = $_POST['birth_date'];
if($connection){
$insert = "insert into describee(first_name,last_name,birth_date)
values ('$first_name','$last_name','$birth_date')";
$execute_insert = mysqli_query($connection,$insert) or die("insert query error");
>here i want to select the lase inserted row from database to show it in textarea tag
if( !empty($first_name) && !empty($last_name) && !empty($birth_date) ){
$last_id = mysqli_insert_id();
$select = "select * from describee where id = $last_id";
$execute_select = mysqli_query($connection,$select) or die("select query error");
>$last_id doesn't hold any data so it return error in the select query.
?>
You're missing your connection to MySQL which should be passed as a parameter to mysqli_insert_id()
$last_id = mysqli_insert_id($connection);

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories