PDO Mysql, want to UPDATE even INSERT the data - php

I have a some problem here, where I want to update the data in CRUD, the data even adding new(like insert).
Have any idea to solve it? Thanks.
There is my code,
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}

binding id as well in the prepared statement
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = array($name,$email,$address);
if($id) {
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$values[] = $id;
} else {
$sql = "INSERT INTO customers (name, email, address)
VALUES (?,?,?)";
}
$q = $pdo->prepare($sql);
$q->execute($values);
Database::disconnect();
header("Location: index.php");
}
}else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM customers WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
Database::disconnect();
}
See line 8 (leave out the **)
edit
added a insert query for the case $id is empty
based on understanding of a comment

number of bound variables does not match number of tokens
$sql = "UPDATE customers
SET name = ?, email = ?, address = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));
You have four tokens ? there should be four parameters, as of :
$q->execute(array($name,$email,$address,$id));
and pay attention not put header("Location: index.php"); in the same file as index.php, because that will cycle and you will get an error like:
your webhost redirected you too many times

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;

PHP: if statement testing if DB value equals a number - if true execute multiple sql query

Hello, I am trying to make php code that executes multiple sql queries as long as a certain database value equals 1. If that value does not equal one, then redirect the page to oops.php.
Here is my code so far:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "cashball_accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
if($result)
{
echo "cashin complete!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
So I want everything from the //Fetch comment to the if($result) to execute if the variable "cashincheck" is equal to 1 in the database.
For example:
if(SELECT cashincheck FROM users WHERE id = ? = 1) {
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
//redirect to oops.php
}
**/\ I know this wont work at all it's just an example /**
I also want to make several other if statements and update the database accordingly, meaning more sql queries and if statements will be needed,so how would I add more?
another example for a separate if statement:
if($_POST['cashmade'] < $_POST['type']) {
$sql = "UPDATE users SET moneymade = moneymade + $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
$sql = "UPDATE users SET moneylost = moneylost + $_POST['type'] - $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
}

How to end / kill a function that checks for IP addresses inside a table without affecting other functions

According to the title, how can I accomplish it? One of the function that checks for IP addresses which are already stored in db should kill the specific check function without affecting others.I used to use exit() and die() but it stops all functions.
main.php:
function CheckIfUserIpExist() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$sql = "SELECT * FROM views WHERE user_ip = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $user_ip);
$stmt->execute();
$stmt->store_result();
$users_ip = $stmt->num_rows;
if($users_ip > 0) {
die();
}
}
function AddUserWhenPageIsViewed() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$time_ = date('Y-m-d G:i:s');
$sql = "INSERT INTO views (user_ip, time_) VALUES (?,?)";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $user_ip, $time_);
$stmt->execute();
}
Index.php
CheckIfUserIpExist();
AddUserWhenPageIsViewed();
Regards.
return is what you need
function CheckIfUserIpExist() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$sql = "SELECT * FROM views WHERE user_ip = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $user_ip);
$stmt->execute();
$stmt->store_result();
$users_ip = $stmt->num_rows;
if($users_ip > 0) {
return;
}
}
function AddUserWhenPageIsViewed() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$time_ = date('Y-m-d G:i:s');
$sql = "INSERT INTO views (user_ip, time_) VALUES (?,?)";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $user_ip, $time_);
$stmt->execute();
}
It would be better to return a status from your Check function
function CheckIfUserIpExist() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$sql = "SELECT * FROM views WHERE user_ip = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $user_ip);
$stmt->execute();
$stmt->store_result();
$users_ip = $stmt->num_rows;
if($users_ip > 0) {
return false;
}
return true;
}
function AddUserWhenPageIsViewed() {
$connection = DBconnect();
$user_ip = $_SERVER["REMOTE_ADDR"];
$time_ = date('Y-m-d G:i:s');
$sql = "INSERT INTO views (user_ip, time_) VALUES (?,?)";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $user_ip, $time_);
$stmt->execute();
}
Then when you call the test function you know what to do next. If you get true the user exists so dont call the Add function, if you get false, the user did not exist, so create one.
if ( ! CheckIfUserIpExist() ) {
AddUserWhenPageIsViewed();
}

PDOStatement::execute, How to execute?

How to execute this query?
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy
WHERE user_id = $user_id
AND date = '$date'";
$q = $pdo->prepare($sql);
To execute you need to use the execute function. This usage of the prepare function also is not safe, each variable should be a placeholder.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM attendancy
WHERE user_id = ?
AND date = ?";
$q = $pdo->prepare($sql);
$q->execute(array($user_id, $date));
while($result = $q->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}

Having trouble creating a safe way for users to update their data

I am making a way for users to edit their data. My first way I did it worked, but then I remembered that it is very insecure and that I should never insert data directly into the database; at least that's what I was told. I try to make it more secure by doing the VALUES (?,?,?,?,?) thing so that the data is not directly going in, which seemed to work fine in my registration page (which I can include if you want).
To start, here is my original update data page that worked fine but it does not use the (?,?,?,?,?) method:
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
Here is what I tried to do to make it more secure but this doesn't seem to work. Specifically the $query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'"; seems to be the issue, though the syntax looks fine to me
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
So I am not sure what the problem is. In my experience with PHP, the syntax should be fine but I must be missing something.
It's quite simple actually, you went from
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
TO
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
It appears you confused an INSERT statement vs. an UPDATE statement when rewriting so to fix you simply use your old statement with the new style...
$query = "UPDATE usertable SET SkypeID = ?, Email = ?, Region = ?, CRank = ?, DRank = ? WHERE UserID = $userid";

Categories