update table if exist - php

In my table I check values is there or not if it's there I need to increase qty but it's not working. What mistake I done?
$servername = "localhost";
$username = "username";
$password = "psw";
$dbname = "database";
$myemail ='my#gmail.com';
$image = '1';
$user = 'user';
$device = '1';
$product = '2';
$qty = '100';
$status = '1';
$orderno = '2';
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
$sql = "INSERT INTO tablemname(email,image_url,user_id,device_id,product_id,qty,status,order_no) VALUES ('$myemail','$image','$user','$device','$product','$qty','$status','$orderno') ON DUPLICATE KEY UPDATE qty=1";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

I think you want to add +1 to qty :
$sql = "INSERT INTO tablemname(email,image_url,user_id,device_id,product_id,qty,status,order_no)
VALUES ('$myemail','$image','$user','$device','$product','$qty','$status','$orderno')
ON DUPLICATE KEY UPDATE qty= qty+1";
A warning, this work only on a value that should be unique. So when i see your table, I am not sure it will work...

Related

How do I "cancel" the update function in sql and php if there is an error?

I am taking data from Steam and due to their busy servers the data that I take doesn't come and then the data in my database gets updated to 0.00 which messes up everything. How could make it so that when I get the below error:
Undefined index: lowest_price in E:\Xampp\htdocs\dashboard\csgocasestats\php-scripts\eSports2013\eSports2013-3.php on line 19
that the data would not get updated if the error happens. And the error happens every time on different links (line).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cases";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$filename_fnSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Factory%20New%29";
$data_fnSt = file_get_contents($filename_fnSt);
$array_fnSt = json_decode($data_fnSt, true);
$lowest_price_fnSt = $array_fnSt["lowest_price"];
$fnSt = strtr("$lowest_price_fnSt","$"," ");
$filename_mnSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Minimal%20Wear%29";
$data_mnSt = file_get_contents($filename_mnSt);
$array_mnSt = json_decode($data_mnSt, true);
$lowest_price_mnSt = $array_mnSt["lowest_price"];
$mnSt = strtr("$lowest_price_mnSt","$"," ");
$filename_ftSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Field-Tested%29";
$data_ftSt = file_get_contents($filename_ftSt);
$array_ftSt = json_decode($data_ftSt, true);
$lowest_price_ftSt = $array_ftSt["lowest_price"];
$ftSt = strtr("$lowest_price_ftSt","$"," ");
$filename_wwSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Well-Worn%29";
$data_wwSt = file_get_contents($filename_wwSt);
$array_wwSt = json_decode($data_wwSt, true);
$lowest_price_wwSt = $array_wwSt["lowest_price"];
$wwSt = strtr("$lowest_price_wwSt","$"," ");
$filename_bsSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Battle-Scarred%29";
$data_bsSt = file_get_contents($filename_bsSt);
$array_bsSt = json_decode($data_bsSt, true);
$lowest_price_bsSt = $array_bsSt["lowest_price"];
$bsSt = strtr("$lowest_price_bsSt","$"," ");
$sql_querys = [
"UPDATE esports2013skins SET M4A4FadedZebra='$fnSt' WHERE id=6",
"UPDATE esports2013skins SET M4A4FadedZebra='$mnSt' WHERE id=7",
"UPDATE esports2013skins SET M4A4FadedZebra='$ftSt' WHERE id=8",
"UPDATE esports2013skins SET M4A4FadedZebra='$wwSt' WHERE id=9",
"UPDATE esports2013skins SET M4A4FadedZebra='$bsSt' WHERE id=10",
];
foreach($sql_querys as $sql){
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
The last advice you got in the previous question was wrong. You should be using prepared statements and parameter binding.
You also have a lot of code repetition. You can reduce all of it if you map an id with a URL and execute the same code for each item.
To avoid the problem with 0.00 inserted into the table, you need to check if the key lowest_price exists in the array. You can do so with isset
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cases";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4'); // always set the charset
// prepare SQL statement
$stmt = $conn->prepare('UPDATE esports2013skins SET M4A4FadedZebra=? WHERE id=?');
$stmt->bind_param('ss', $firstCol, $id);
$items = [
6 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Factory%20New%29",
7 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Minimal%20Wear%29",
8 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Field-Tested%29",
9 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Well-Worn%29",
10 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Battle-Scarred%29",
];
foreach ($items as $id => $filename_St) {
$array_St = json_decode(file_get_contents($filename_St), true);
// If there is lowest price the populate the bound variable and execute the query
if (isset($array_St["lowest_price"])) {
$lowest_price_ftSt = $array_St["lowest_price"];
$firstCol = strtr($lowest_price_ftSt, "$", " ");
$stmt->execute();
}
}

MYSQL create a line with every new user

I have a little problem
I want to create a script, that creates a new line in the table, if there is a new user and in the line, change the "points" columme to zero(0)
This is my current code:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
$servername = "db.mysql-01.gsp-europe.net";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
$conn->close();
?>
What i need in the cube: When there new user_id ($firstName) appear, create new line with this user name, and change the "points" columme from "null" into Zero(0)
Thanks for yout time, I appreciate it
If I understand well you want to check if the user exists or not. If user is new create new line with the user with 0 points and if exist increse points with 1.
<?php
header('Content-Type: text/html; charset=Windows-1250');
if(isset($_POST['firstname'])){
$firstName = $_POST['firstname'];
$servername = "db.mysql-01.gsp-europe.net";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
//if don't exist create user with points 0
if($rows==0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
}
?>
Remember, I gave you an idea, the code is prone to sql inject

Error in sql while uploading data with three images

I'm trying to upload three images and few texts related to car using PHP and MYSQL.
Initially the i got the message " MYSQL has gone away.." so I increased the max_packet size to 500M . .The database name, table name are correct.
Following is the php code I have used.
<?php
if(isset($_POST["submit"]))
{
$check1 = getimagesize($_FILES["image1"]["tmp_name"]);
$check2 = getimagesize($_FILES["image2"]["tmp_name"]);
$check3 = getimagesize($_FILES["image3"]["tmp_name"]);
if($check1 !== false and $check2 !== false and $check3 !== false)
{
$img1 = $_FILES['image1']['tmp_name'];
$imgContent1 = addslashes(file_get_contents($img1));
$frontimg = $imgContent1;
$img2 = $_FILES['image2']['tmp_name'];
$imgContent2 = addslashes(file_get_contents($img2));
$backimg = $imgContent2;
$img3 = $_FILES['image3']['tmp_name'];
$imgContent3 = addslashes(file_get_contents($img3));
$intimg = $imgContent3;
$kms = htmlentities($_POST["kms"]);
$make = htmlentities($_POST["make"]);
$model = htmlentities($_POST["model"]);
$variant = htmlentities($_POST["variant"]);
$reg = htmlentities($_POST["year"]);
$color = htmlentities($_POST["color"]);
$owner = htmlentities($_POST["owner"]);
$price = htmlentities($_POST["price"]);
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'car';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if($db->connect_error)
{
die("Connection failed: " . $db->connect_error);
}
$insert = $db->query(" insert into car( frontimg, backimg, intimg, kms, make, model, variant, reg, color, owner, price )
values ('$frontimg', '$backimg', '$intimg','$kms','$make', '$model', '$variant', '$reg', '$color',
'$owner','$price') ");
if($insert)
{
echo "data stored successfully";
}
else
{
echo "Check your query";
}
}
}
?>
The php is returning the text " Check your query " indicating the error in the SQL code.
What might have gone wrong here..

How to put the output query from mySQL to php int variable

I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)

multi_query() has an error

I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

Categories