mysql insert/update always inserting never updating - php

I have the following code to insert if a row doesn't exist with the given part_code or update if the part_code already exists. The problem is that it always inserts and produces duplicates. Can anyone see why.
$query = 'SELECT * FROM qty_csv';
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
while($row = mysqli_fetch_array($result)){
$part_code = $row['code'];
$part_descr = $row['descr'];
$part_qty_in_stock = $row['qty_in_stock'];
$reorder_level = $row['reorder_level'];
$reorder_qty = $row['reorder_qty'];
$part_price = $row['price'];
// check to see if the value you are entering is already there
$result1 = $conn->query("SELECT * FROM part WHERE part_code == '$part_code'");
if (!$result1){
$sql =
"INSERT INTO part VALUES (
'',
'',
'$part_descr',
'$part_price',
'',
'$part_code',
'',
'',
'',
'',
'$reorder_level',
'$reorder_qty',
'',
'',
'$part_qty_in_stock',
'',
'',
''
)";
if (!$conn->query($sql)) {
echo "INSERT failed: (' . $conn->errno . ') " . $conn->error;
}
}else{
$sql = "UPDATE part SET "
. "part_qty_in_stock = '$part_qty_in_stock',"
. "reorder_level = '$reorder_level',"
. "reorder_qty = '$reorder_qty' "
. "WHERE part_code == '$part_code'";
// This code exists and will be updated
$conn->query($sql);
}
}
I have it under the debugger and see that even if part_code == '$part_code' the $result1 is bool()false. I would have expected it to be true.

The problem here is that your "$result1" object is False only when an error happens, otherwise, even if the query returns no results (because it's empty), it will be a mysqly object.
You should check the number of rows rather than just checking !$result.
Just change
if (!$result1){
with
if (mysqli_num_rows($result1) == 0){
Check out the docs for more info:
http://it1.php.net/mysqli_query
http://www.php.net/manual/en/mysqli-result.num-rows.php

please check your query,please use = for checking instead of ==
SELECT * FROM part WHERE part_code = '$part_code'

Use
$result1 = $conn->query("SELECT count(*) as count FROM part WHERE part_code = '$part_code'");
Then simply check $result1['count'] > 0

Related

PHP Mysqli Delete from DB

So I thought this would be a simple query to just delete rows that didn't have any data stored under certain columns, but for some reason my query is returning that zero rows have been deleted, I checked the table and they are still there.
What I want to do is delete from my gps_routes table where the route_lat and route_long do not contain a location (empty).
I have checked my to make sure I have delete permissions enabled as well.
$sql = "SELECT * FROM gps_routes";
$result = $link->query($sql);
$rowCount = $result->num_rows; $rows_deleted = 0; $delete_row = false;
if ($rowCount > 0)
{
while($row = $result->fetch_assoc())
{
$user = $row['user_email'];
$id = $row['route_id'];
$lat = $row['route_lat'];
$lng = $row['route_long'];
if (empty($lat) || empty($lng)){
$delete_row = true;
}
if (ctype_space($lat) || strlen(trim($lat)) == 0){
$delete_row = true;
}
if ($lat == '' || $lat == ""){
$delete_row = true;
}
if ($delete_row){
$rows_deleted++;
mysqli_query($link, "DELETE FROM gps_routes WHERE user_email = '$user' AND route_id = '$id'");
}
}
echo "Routes deleted: $rows_deleted";
}
From your code is suggest that you just want to go through your DB and check to see if the lat and long are empty. If they are then delete them.
Sounds like you can just use this query to get the job done.
mysqli_query($link, "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)");
This is how I would do it based off the code you have provided:
$query = "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)";
$result = $link->query($query);
echo 'Routes deleted: ' . $result->num_rows;

Query was Empty error in php using PDO [duplicate]

I am trying to build a cart using MySQL. I keep getting this error 'Query was empty' when I run this code. Please help I've tried several things such as putting the variables inside the string instead of concatenating it.
<?php ob_start(); ?><?php require_once("../include/membersite_config.php"); ?>
<?php
require('../products_reloaded/config.php');
session_start();
$user = $_REQUEST['user'];
$user = mysql_real_escape_string($user);
$itemNum = $_REQUEST['itemNum'];
$itemNum = mysql_real_escape_string($itemNum);
$quantity = $_POST['quantity'];
$quantity = intval($quantity);
$CheckForExistence = mysql_query("select * from cart where user = '$user' and p_number = '$itemNum'" );
$alreadyExistsChecker = mysql_num_rows($CheckForExistence);
if($alreadyExistsChecker >= 1)
{
$quantity +=1;
echo "this is equal to $alreadyExistsChecker";
}
if($alreadyExistsChecker == 0)
{
$getQuery = mysql_query("select * from product where p_number = '$itemNum'");
while($row = mysql_fetch_array($getQuery))
{
$name = $row['p_name'];
$image = $row['p_url'];
$price = $row['p_price'];
}
$name = mysql_real_escape_string($name);
$image = mysql_real_escape_string($image);
$price = intval($price);
$query = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
}
header('http://www.definitionxjm.com/shopping/viewCart.php');
?>
What do you try to achieve with this line?
$result = mysql_query($query);
Just delete it and change the line above to
$result = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
[Edit]
Btw. you are forgetting the " (quotes) inside the query which causes an sql error to occur, leading to $query = false (see manual). $query (false) then gets converted to string, resulting in '' (an empty string) which you pass to mysql_query and that generates an "Query was empty"-Message, as it should because you tried to send an empty query.
It can also mean the table which is in consideration is empty.This condition arises when the "DELETE FROM table_name where ;" is used. Here if the table "table_name" has no data, it cannot delete anything and hence it shows an error stating that the query is empty.

SQL without a WHERE that uses a key column

My script is quitting on SQL calls that should not have an issue. One of the queries that is failing to update is:
UPDATE dist_comp.private_schools SET mail_address = '1351 Royalty Dr', city = 'Alabaster', state = 'AL',zip_code = 35007,phone = '2056633973' WHERE school_name = 'Kingwood Christian School' AND city = 'Alabaster'
When I run the same query in MySQL workbench, I get
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Queries and reconnect.
Is this the reason why my script is quitting?
<?php
require_once('connect.php');
function schoolInfo($school_name,$city){
$data = array();
$counter = 0;
$handle = fopen("k12privateschools_loc_0813.csv","r") or exit('doesnt work');
fgetcsv($handle) or exit('fgetcsv issue');
while( ($line = fgetcsv($handle)) !== false) {
$data[] = $line;
///echo ("Does schoolname and city match: " . addslashes($data[$counter][2]). ":" . $school_name . " ; " . addslashes($data[$counter][4]). ":" . $city . "\n");
if (addslashes($data[$counter][2])==$school_name && addslashes($data[$counter][4])==$city){
//echo ('match');
if($data[$counter][13] != ""){
$mail_address = $data[$counter][12];
$city= $data[$counter][13];
$state= $data[$counter][14];
$zip_code= $data[$counter][15];
$zip_4= $data[$counter][16];
}else{
$mail_address = $data[$counter][3];
$city= $data[$counter][4];
$state= $data[$counter][5];
$zip_code= $data[$counter][6];
$zip_4= $data[$counter][7];
}
$phone= $data[$counter][8];
$query= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."',";
if($zip_code != ""){
$query.="zip_code = ".$zip_code.",";
}
if($zip_4 != ""){
$query.="zip_4 = ".$zip_4.",";
}
$query.= "phone = '".$phone."'
WHERE school_name = '".$school_name."' AND city = '" .$city . "'";
mysqli_query($con,$query);
if(mysqli_affected_rows($con)==0){
exit($query . "\n ");
}
//echo $query;
}//end if counter \
else{
//echo("no match");
}
$counter++;
}//end read lines from file
}
echo "starting import \n";
//Query for all school names
$sql2 = mysqli_query($con,"SELECT school_name,city FROM dist_comp.private_schools") or exit('query issue second');
while($row = mysqli_fetch_array($sql2)){ //this line is making it take a really long time
$school_name= addslashes($row['school_name']);
$city = addslashes($row['city']);
schoolInfo($school_name,$city);
}//end while fetch array
//}
echo "Import finished";
?>
Try to disable safe update using this line before your query :
mysqli_query($con,"SET sql_safe_updates=0");
Or use :
$query="SET sql_safe_updates=0";
$query.= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."';";
mysqli_multi_query($con,$query);
or in MySQL WorkBench:
Edit -> Preferences -> SQL Queries
Uncheck Forbid UPDATE and DELETE statements without a WHERE clause
(safe updates)
Query --> Reconnect to Server
$query = 'SET SQL_SAFE_UPDATES=0;';
$query .= 'custom query here;';
$query .= 'SET SQL_SAFE_UPDATES=1;';

Query was empty PHP error

I am trying to build a cart using MySQL. I keep getting this error 'Query was empty' when I run this code. Please help I've tried several things such as putting the variables inside the string instead of concatenating it.
<?php ob_start(); ?><?php require_once("../include/membersite_config.php"); ?>
<?php
require('../products_reloaded/config.php');
session_start();
$user = $_REQUEST['user'];
$user = mysql_real_escape_string($user);
$itemNum = $_REQUEST['itemNum'];
$itemNum = mysql_real_escape_string($itemNum);
$quantity = $_POST['quantity'];
$quantity = intval($quantity);
$CheckForExistence = mysql_query("select * from cart where user = '$user' and p_number = '$itemNum'" );
$alreadyExistsChecker = mysql_num_rows($CheckForExistence);
if($alreadyExistsChecker >= 1)
{
$quantity +=1;
echo "this is equal to $alreadyExistsChecker";
}
if($alreadyExistsChecker == 0)
{
$getQuery = mysql_query("select * from product where p_number = '$itemNum'");
while($row = mysql_fetch_array($getQuery))
{
$name = $row['p_name'];
$image = $row['p_url'];
$price = $row['p_price'];
}
$name = mysql_real_escape_string($name);
$image = mysql_real_escape_string($image);
$price = intval($price);
$query = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
}
header('http://www.definitionxjm.com/shopping/viewCart.php');
?>
What do you try to achieve with this line?
$result = mysql_query($query);
Just delete it and change the line above to
$result = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
[Edit]
Btw. you are forgetting the " (quotes) inside the query which causes an sql error to occur, leading to $query = false (see manual). $query (false) then gets converted to string, resulting in '' (an empty string) which you pass to mysql_query and that generates an "Query was empty"-Message, as it should because you tried to send an empty query.
It can also mean the table which is in consideration is empty.This condition arises when the "DELETE FROM table_name where ;" is used. Here if the table "table_name" has no data, it cannot delete anything and hence it shows an error stating that the query is empty.

PHP MySQL issue (if statement doesnt have effect)

This is my code:
if ((isset($_POST['vidcode'])) && (strlen(trim($_POST['vidcode'])) > 0)) {$vidcode = stripslashes(strip_tags($_POST['vidcode']));} else {$vidcode = 'Invalid URL';};
if ((isset($_POST['vidtitle'])) && (strlen(trim($_POST['vidtitle'])) > 0)) {$vidtitle = stripslashes(strip_tags($_POST['vidtitle']));} else {$vidtitle = 'No Title';};
$vidcode = str_replace('"', '', $vidcode);$vidcode = str_replace("'", "", $vidcode);$vidtitle = str_replace('"', '', $vidtitle);$vidtitle = str_replace("'", "", $vidtitle);
$db_handle = mysql_connect($server, $user_name, $password);$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT status FROM youtube2mp3 WHERE videocode = '$vidcode' ";$result = mysql_query($SQL); [BUGFIX:Added]$row = mysql_fetch_assoc($result);[/BUGFIX]
if(mysql_num_rows($result) != false){
// Add to DB & Set Status
$SQL = "UPDATE youtube2mp3 SET status='Download Complete' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
[BUGFIX:Removed]
// Get Data into variable
$row = mysql_fetch_assoc($result);
[/BUGFIX]
// Check if its been processed
if (strcasecmp($row['status'], "Done") != 0){
// Add to DB & Set Status
$SQL = "UPDATE youtube2mp3 SET status='Initializing Conversion' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
$filename = $vidcode.'.mp4';
if (!file_exists($filename) && !filesize($filename) >= 10000) {
$SQL = "UPDATE youtube2mp3 SET status='Invalid' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
} else {
$SQL = "UPDATE youtube2mp3 SET status='Converting' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
//convert file
exec('ffmpeg -i '.escapeshellarg($vidcode).'.mp4 -ab 156 -f mp3 '.escapeshellarg($vidtitle).'.mp3 2>&1');
$SQL = "UPDATE youtube2mp3 SET status='Zipping' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
// Zip it up
exec('zip "zips/'.$vidcode.'.zip" "'.$vidtitle.'.mp3"');
//delete files
//unlink($vidcode.'.mp4');
unlink($vidtitle.'.mp3');
$SQL = "UPDATE youtube2mp3 SET status='Done' WHERE videocode='$vidcode'";
$result = mysql_query($SQL);
};
};
};
mysql_close($db_handle);
Right Just FYI - It was me being stupid! I reused $result which gave unexpected results. See [BUGFIX] in code above...
Don't use SELECT *..., explicitly list your columns in your queries. This way, it is clear what columns you expect to get from the database by looking at your code. Plus, if it turns out that a column you think exists does not, you'll get an error at the stage where the problem is actually happening - at the data retrieval, instead of later in your code when you're trying to use the data.
Also note, your use of mysql_fetch_array (docs) is returning a numerically-indexed array of columns. Use mysql_fetch_assoc (docs) for an associative array.
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$sql = '
SELECT
`status`,
`some_other_field`
FROM
`table`
WHERE
`videocode` = "'.$vidcode.'"';
$result = mysql_query($sql, $db_handle) or die('Error while performing query: '.mysql_error($db_handle));
if (mysql_num_rows($result, $db_handle) < 1) {
// you didn't get any rows back...
}
if(mysql_num_rows($result) != false){
// Get Data into variable
$row = mysql_fetch_assoc($result, $db_handle);
// Check if its been processed
if ($row['status'] != "Done"){
// CODE HERE IS STILL GETTING EXECUTED EVEN WHEN $row['status'] IS "Done"
}
}
Using this code, if the columns you try to select don't exist, then you'll get a database error.
I haven't read thoroughly what the problem is, in general you can:
Try this:
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');
Try alert(response), I mean the the xml http response, it is not true that ajax has no output, ajax will bring the output exactly with all php errors if any! If you use jquery I guess there is something analogous to http response.
When code is executed in strange places, the solution is trivial just put echo inside every if, every else, every function, constructor whatever... As soon you see a block of code is alive when was supposed not to be focus there only!
When you suspect a problem in a very specific place but instead you focus in a big piece of code (as in your case) then in most case you have to forget all the rest of the code, it's not going to be of any help. Sorry if it is too general!
You are using mysql_fetch_array which returns the row as a 0 indexed array.
You need to use mysql_fetch_assoc
Try this:
if ((isset($_POST['vidcode'])) && (strlen(trim($_POST['vidcode'])) > 0)) {
$vidcode = stripslashes(strip_tags($_POST['vidcode']));
} else {
$vidcode = 'Invalid URL';
};
if ((isset($_POST['vidtitle'])) && (strlen(trim($_POST['vidtitle'])) > 0)) {
$vidtitle = stripslashes(strip_tags($_POST['vidtitle']));
} else {
$vidtitle = 'No Title';
};
$vidcode = str_replace('"', '', $vidcode);
$vidcode = str_replace("'", "", $vidcode);
$vidtitle = str_replace('"', '', $vidtitle);
$vidtitle = str_replace("'", "", $vidtitle);
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM table WHERE videocode = '$vidcode' ";
$result = mysql_query($SQL);
if(mysql_num_rows($result) != false) {
// Get Data into variable
$row = mysql_fetch_assoc($result);
// Check if its been processed
if (strcasecmp($row['status'], "Done") != 0)
{
// CODE HERE IS STILL GETTING EXECUTED EVEN WHEN $row['status'] IS "Done"
}
};
};
mysql_close($db_handle);
Maybe try this:
if(strcasecmp(trim($row['status']), "DONE") != 0) {
Or try the while loop
function validatePostValues($alt_response = 'Default', $post_value = NULL) {
if((isset($post_value)) && (strlen(trim($post_value)) > 0)) {
$return_value = stripslashes(strip_tags($post_value));
$return_value = str_replace('"', '', $return_value);
$return_value = str_replace("'", "", $return_value);
} else {
$return_value = $alt_response;
}
return $return_value;
}
$vidcode = validatePostValues('Invalid URL', $_POST['vidcode']);
$vidtitle = validatePostValues('No Title', $_POST['vidtitle']);
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM table WHERE videocode = '$vidcode' ";
$result = mysql_query($SQL);
if(mysql_num_rows($result)) {
// Loop through the results
while($row = mysql_fetch_assoc($result)) {
// Added for debugging, enclose w/ PIPE for
// whitespace check
echo "Status is: |".$row['status']."|<br />\n";
// Check if its been processed
if($row['status'] != "Done"){
// CODE HERE IS STILL GETTING EXECUTED
// EVEN WHEN $row['status'] IS "Done"
echo "Row: ".print_r($row,true)."<br />\n";
}
}
}
mysql_close($db_handle);

Categories