Why is my PHP / MySQL inserting instead of updating? - php

if ($Funct == "BUILD" AND $Mode == "GROUND")
{
$sql = "SELECT * FROM $landCon WHERE North = '" . $North . "' AND West = '" . $West ."'" ;
$result = mysql_query($sql) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
If ($Count == 0 )
{
$sql = "INSERT INTO $landCon (West,North,Type1) VALUES ($West,$North,'$Char')";
mysql_query($sql) or die("Error occurred in RootA as:[$sql]: " . mysql_error());
}
else
{
$result=mysql_query("UPDATE $landCon SET Type1= '$Char' WHERE North = $North AND West=$West") or die( "Database Error: ".mysql_error());
}
echo "SUCCESS";
}
Instead of it updating where an entry exists it is inserting. My intention is to have it update if there is already the specified $North and $South entry so that there is only one North/South value per map grid.

$count = mysql_num_rows($result);
If ($Count == 0 )
Is $count $Count ?
captcha: languages that silently initialize new variables when you make a typo

Related

Error in SQL syntax at line 1 php/sql

The first problem was with mysql_query which returns FALSE and mysql_num_rows expects parameter 1 to be resource not a boolean. I ve made this to get the error
if($itemsres === FALSE)
die(mysql_error());
Now i have this error " You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
<?php
ob_start();
session_start();
require("header.php");
require("functions.php");
echo "<h1>Your shopping cart</h1>";
showcart();
if(isset($_SESSION['SESS_ORDERNUM']) == TRUE) {
$sql = "SELECT * FROM orderitems WHERE order_id = " .
$_SESSION['SESS_ORDERNUM'] . ";";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if($numrows >= 1) {
echo "<h2><a href='checkout-address.php'>Go to the checkout</a></h2>";
}
}
require("footer.php");
?>
The problem started from here.
if(isset($_SESSION['SESS_LOGGEDIN']))
{
$custsql = "SELECT id, status from orders WHERE customer_id = ".
$_SESSION['SESS_USERID']. " AND status < 2;";
$custres = mysql_query($custsql);
$custrow = mysql_fetch_assoc($custres);
$itemssql = "SELECT products.*, orderitems.*, orderitems.id AS itemid FROM
products, orderitems WHERE orderitems.product_id =products.id AND order_id
= " . $custrow['id'];
$itemsres = mysql_query($itemssql);
if($itemsres === FALSE)
die(mysql_error());
$itemnumrows = mysql_num_rows($itemsres);
}
mysql_num_rows expects parameter 1 instead of boolean which is given by mysql_query and after i made that check now i have this sql error.
<?php
ob_start();
session_start();
require("config.php");
if(isset($_SESSION['SESS_LOGGEDIN']) == TRUE) {
header("Location: " . $config_basedir);
}
if(isset($_POST['submit']))
{
$loginsql = "SELECT * FROM logins WHERE username = '" . $_POST['userBox'].
"' AND password = '" . sha1($_POST['passBox']) . "'";
$loginres = mysql_query($loginsql);
$numrows = mysql_num_rows($loginres);
if($numrows == 1)
{
$loginrow = mysql_fetch_assoc($loginres);
session_start("SESS_LOGGEDIN");
session_start("SESS_USERNAME");
session_start("SESS_USERID");
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM orders WHERE customer_id = " .
$_SESSION['SESS_USERID'] . " AND status < 2"; $orderres =
mysql_query($ordersql); $orderrow = mysql_fetch_assoc($orderres);
session_start("SESS_ORDERNUM"); $_SESSION['SESS_ORDERNUM'] =
$orderrow['id']; header("Location: ".$config_basedir);
}
else {
header("Location: http://" .$_SERVER['HTTP_HOST']. $_SERVER['SCRIPT_NAME'] .
"?error=1");
}
}
else {
require("header.php");
?>
You have a syntax error
Use query like this
$sql = "SELECT * FROM orderitems WHERE order_id = $_SESSION['SESS_ORDERNUM']";
Or
$sql = "SELECT * FROM orderitems WHERE order_id = ".$_SESSION['SESS_ORDERNUM'];
Or
$sql = "SELECT * FROM orderitems WHERE order_id = '$_SESSION['SESS_ORDERNUM']'";
NOTE: SQL Injection.
PS: Use prepared statements
$loginrow = mysql_fetch_assoc($loginres);
session_start();
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM orders WHERE customer_id = " .
$_SESSION['SESS_USERID'] . " AND status < 2";
$orderres =
mysql_query($ordersql); $orderrow = mysql_fetch_assoc($orderres);
$_SESSION['SESS_ORDERNUM'] =
$orderrow['id']; }
First of all, you should check the value of $_SESSION['SESS_ORDERNUM'].
The error means the created query($sql) is not valid, so you should debug $sql.

Conditional mysqli date range check to print a price in sql

This time I'm trying to make some php code to work with mysqli in order to check if today date is between a range of dates in a Mysql table, if the condition is true I need to print a price from a table otherwise it shuould print a different price from another table. so I already have all sql connections set in another php file, the problem is that when I try the code, it just shows nothing, a blank page only. This is the code im using:
<?php
$currentdate = date("Y/m/d");
//basic include files
require_once('/home/user/public_html/folder/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND $currentdate >= 'seasonal_from' AND $currentdate <= 'seasonal_to';");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice ){
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)){
echo "$ {$standard['room_price']} ";
}
} else {
if(! $seasonalpricedate ){
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalpricedate, MYSQL_ASSOC)){
echo "$ {$standard2['seasonal_price']} ";
}
}
}
?>
I already tried both codes with standardprice and seasonalprice working without a conditional, but when I try to do it like this, it does not show anything.
PostData: Im still trying to learn english, so please appologize me if I fail some words, thanks in Advance.
UPDATE: Ok so in this way it works if there is no values true its ok, it shows the standardprice, but if match the date, dont show anything, here is the code changed:
<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
$seasonalpricedate = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1' AND '$currentdate' >= seasonal_from AND '$currentdate' <= seasonal_to");
$result = ($seasonalpricedate) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
$seasonalprice = mysqli_query($conn, "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'");
if(! $seasonalprice )
{
die('Could not get data: ' . mysqli_error());
while($standard2 = mysqli_fetch_array($seasonalprice, MYSQL_ASSOC))
{
echo "$ {$standard2['seasonal_price']} ";
}
}
} else {
$standardprice = mysqli_query($conn, "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'");
if(! $standardprice )
{
die('Could not get data: ' . mysqli_error());
}
while($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC))
{
echo "$ {$standard['room_price']} ";
}
}
mysqli_close($conn);
?>
So close to make it work, thanks to
UPDATE: Because you are also updated your OP, now i found what causes the problem. Ther proble were when you says: die('Could not get data: ' . mysqli_error()); And after that you want to try a while loop. while won't executed, because you terminated the script with a die(); Move the while to the else case of your if condition. See my comments.
Use this:
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
//Also display your errors.
display_errors(true);
$currentdate = date("Y-m-d");
//basic include files
require_once('/home/trankilo/public_html/book/db.php');
//Put your query into a variable, so you can dump / print it.
$sql = "SELECT `seasonal_price`"
. " FROM `hotel_seasonal_price`"
. " WHERE room_type_id = '1'"
. " AND '" . $currentdate . "' >= seasonal_from"
. " AND '" . $currentdate . "' <= 'seasonal_to'";
echo $sql;
//Try to run it in the sql directly. Is it gives back you any result?
//Do not need to
$result = mysqli_query($conn, $sql) or die(mysqli_error());
if (mysqli_num_rows($result) != 0) {
//Check if we have result by echoing some dummy text
echo "Yes, we have result!";
$sql = "SELECT `seasonal_price` FROM `hotel_seasonal_price` WHERE room_type_id = '1'";
//Do the same as the previous query. Does it gives you back anything?
$seasonalprice = mysqli_query($conn, $sql);
if (!$seasonalprice) {
//I do not really get what happens here. If you have no seasonalprice,
//then you can not fetch_array on that!
//Move this whole section.... You've say die, and after that do a while?
die('Could not get data: ' . mysqli_error());
} else {
while ($standard2 = mysqli_fetch_assoc($seasonalprice)) {
echo "$ " . $standard2['seasonal_price'] . " ";
}
}
} else {
//Same as previous
$sql = "SELECT `room_price` FROM `hotel_room_price` WHERE price_id = '1'";
$standardprice = mysqli_query($conn, $sql);
if (!$standardprice) {
die('Could not get data: ' . mysqli_error());
//same here, move the while to the else...
} else {
while ($standard = mysqli_fetch_array($standardprice, MYSQL_ASSOC)) {
echo "$ {$standard['room_price']} ";
}
}
}
mysqli_close($conn);

Drag and Drop array NOT EXIST then Insert into MySQL

I have two tables one for user and one for search. When I drag a search over to user it adds entire search list. How do I only insert the item dragged and not the entire search array?
THE PROBLEM IS recordsArray.
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
//INSERTS array item that does NOT EXIT in userTable
if (mysql_affected_rows()==0) {
$query = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = " . $recordIDValue);
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert/update query failed');
}
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>
Both list arrays id must maintain the same id names in order for the above item to acknowledge and process the list items. Keeping things simple I just used the same code for the Search, User format:
<li id="recordsArray_<?php echo $result['recordID']; ?>"><?php echo $result['recordID'] . ". " . $result['recordText']; ?></li>
Javascript:
$(function() {
$("#contentLeft ul, #main ul").sortable({ accept: '.draggable', connectWith: "#contentLeft ul", opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse){
$("#contentRight").html(theResponse);
});
}
});
}).disableSelection();
});
How can I call only the recordsArray items from #content ul?
I can only get one insert per refresh with this but it does drag and drop insert...
Still need an if statement for possible errors because +/-1 if
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
$uRA = $updateRecordsArray;
// Get total number of elements in $updateRecordsArray
$ifArray = $updateRecordsArray;
$resultCount = count($ifArray);
//echo '<br />';
//print_r($resultCount);
// Get total number of rows in $records1
$recordTable = array();
$result = mysql_query("SELECT recordListingID FROM records1");
$numRows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$recordTable = array_merge($recordTable, array_map('trim', explode(",", $row['recordListingID'])));
}
//Gets $id/$val of elements not in both arrays
$results = array_diff($uRA, $recordTable);
//echo '<br />';
//print_r($numRows);
//Give variables for +/- 1 $numRows
$plusNumRows = $numRows + 1;
$minusNumRows = $numRows - 1;
//echo '<br />';
//print_r($minusNumRows);
// Normal jQuery drag and drop ranking found online
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
//If statement for for +/- 1 $numRows
If ($resultCount == $numRows -1 || $resultCount == $numRows || $resultCount == $numRows + 1){
$sql = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = $recordIDValue");
}
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

PHP variable variables in MySQL query

This code works fine: $batsman1name is inserted as a new value in the correct row in the database.
for($count = 1; $count <= 22; ++$count)
{
$setbattingid = 'batsman' . $count . 'battingid';
$$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
$setname = "batsman" . $count . "name";
$$setname = mysql_real_escape_string($_POST[$setname]);
$query = "UPDATE batting_new SET batsmanname = NULLIF('$batsman1name', '') WHERE battingid = '$batsman1battingid'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
}
With this code the database is not updated, but the varaible variables $$setname and $$setbattingid do contain the same values as $batsman1name and $batsman1battingid above.
for($count = 1; $count <= 22; ++$count)
{
$setbattingid = 'batsman' . $count . 'battingid';
$$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
$setname = "batsman" . $count . "name";
$$setname = mysql_real_escape_string($_POST[$setname]);
$query = "UPDATE batting_new SET batsmanname = NULLIF('$$setname', '') WHERE battingid = '$$setbattingid'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
}
Any ideas? Let me know if I haven't explained my question very well? Thanks.
You should use :
$query = "UPDATE batting_new SET batsmanname = NULLIF('${$setname}', '') WHERE battingid = '${$setbattingid}'";
As described here : http://php.net/manual/language.variables.variable.php

mysqli_num_rows() expects parameter 1 to be mysqli_result geolocation

I really don't know what i'm doing wrong. I want to count the rows in my query. My id's started from 1 to ... step 1, so the biggest number is the last record. I only want to let the script run on the last record of de DB. So here is my code.
public function saveLongLan()
{
define("MAPS_HOST", "maps.google.com");
define("KEY", "MYKEY");
$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db('Foodsquare', $link);
if (!$db_selected)
{
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM tblPlaces WHERE 1";
$result = mysql_query($query);
$row_cnt = mysqli_num_rows($result);
if (!$result)
{
die("Invalid query: " . mysql_error());
}
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
while ($row = #mysql_fetch_assoc($result))
{
$geocode_pending = true;
while ($geocode_pending)
{
$address = $row["Street"];
$id = $row["Id"];
$request_url = $base_url . "&q=" . urlencode($address);
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0)
{
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
//explode functie breekt een string af vanaf een bepaald teken en stopt hem dan in een array
$coordinatesSplit = explode(',', $coordinates);
// formaat: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];//getal = plaats in array
$lng = $coordinatesSplit[0];
$query = sprintf("UPDATE tblPlaces " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '". $row_cnt . "' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result)
{
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0)
{
// sent geocodes too fast
$delay += 100000;
}
else
{
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . " \n";
}
usleep($delay);
}
}
}
your query is incorrect $query = "SELECT * FROM tblPlaces WHERE 1";
you should specify the column name after where clause for comparison with a value for example: WHERE column_name = 1 or something like that.
You're using mysqli_num_rows($result) but you aren't using MySQLi.
Change:
$row_cnt = mysqli_num_rows($result);
To:
$row_cnt = mysql_num_rows($result);
And you should be good to go.

Categories