Error in sql while uploading data with three images - php

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..

Related

Checking SQL Database for value

I am trying to use php to check my database to see if a value exists. My main goal is to use this value
$_GET['UDID']
and if it is equal to any value that is in the database it will return
echo 'FOUND';
I am using this code:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$dbname = "*****";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("CONNECTION FAILED: " . $connect->connect_error);
}
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$id'");
if($result === FALSE) {
die("ERROR: " . mysqli_error($result));
}
else {
while ($row = mysqli_fetch_array($result)) {
if($row['udid'] == $udid) {
$results = 'Your device is already registered on our servers.';
$results2 = 'Please click the install button below.';
$button = 'Install';
$buttonlink = 'https://**link here**';
}
else {
$results = 'Your device is not registered on our servers';
$results2 = 'Please click the request access button below.';
$button = 'Request Access';
$buttonlink = 'https://**link here**';
}
}
}
?>
But for some reason it is not working, I am sure I am over looking something. your help is greatly appreciated.
Try this:
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '" .$udid. "'");
And also, make sure to set the value from 'GET' to $udid. Should be like this:
$udid = $_GET['UDID'];
We can use mysqli_fetch_array() instead to get the result row. I also include error handling. Now your code must look like this :
$udid = $_GET['UDID'];
$id = mysqli_real_escape_string($connect, $udid);
$result = mysqli_query($connect, "SELECT `udid` FROM `wmaystec_WMT-SS`.`data` = '$id'");
if($result === FALSE) {
die(mysqli_error("error message for the user")); //error handling
}
else {
while ($row = mysqli_fetch_array($result)) {
echo "FOUND :" .$row['thefieldnameofUDIDfromyourDB'];
}
}
I would suggest you to first escape the string, using the mysqli_real_escape_string function, and then call the SQL query.
$udid = mysqli_real_escape_string($connect, $udid);
$sql = mysqli_query($connect, "SELECT udid FROM data WHERE udid = '$udid'");

database updating using php

well i just made a form in HTML witch accepts user inputs and a mysql database to store them, now in the php file everything goes well no errors but the problem is the data never displays in the database, here is the php file:
<?php
if(isset($_POST["submitacc"])){
$servernm = "localhost";
$serverusrnm = "root";
$serverpass = "2003";
$db = "blue";
$conn = new mysqli($servernm, $serverusrnm, $serverpass, $db);
if($conn ->connect_error){
die("connection failed".$conn->connect_error);
}
$fnm = $_POST["fnm"];
$lnm = $_POST["lnm"];
$mail = $_POST["mail"];
$pass = $_POST["pass"];
$age = $_POST["age"];
$gender = $_POST["gender"];
if(isset($_POST["gender"])&&$_POST["gender"]=="male"){
$gender = "male";
}else {
$gender = "female";
}
$mysql="update createacc set fnm = '$fnm', lnm = '$lnm', mail = '$mail', passwod = '$pass', age = '$age', gender = '$gender' ";
if($conn->query($mysql)== true){
echo "record updated";
}else {
echo "error updating record".$conn->error;
}
$conn->close();
}
?>
Use mysqli_query() instead of query(). Also use WHERE clause in your $mysql variable. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Example:
if(mysqli_query($conn , $mysql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $mysql. " . mysqli_error($conn);
}

update table if exist

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...

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();
?>

Having trouble pushing data from a sql query to an array for comparison

So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.

Categories