I'm trying to display info from a mysql row on this page. I'm using $_GET, because the id is included in the link to the page: www.example.com/page.php?id=1 but it returns this error:
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 '= '1'' at line 1
Does anyone know how to fix this?
code below:
<?php
$username="xxx";
$password="xxx";
$database="xxx";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
include 'library/config.php';
include 'library/opendb.php';
if(isset($_GET['id']))
{
$query = "SELECT id, title, content, contactname, contactemail, contactnumber ".
"FROM vacancies".
"WHERE id = '{$_GET['id']}'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($id, $title, $content, $contactname, $contactemail, $contactnumber) = mysql_fetch_array($result, MYSQL_NUM);
$content = htmlspecialchars($content);
}
if(isset($_POST['update']))
{
$id = $_POST['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$contactname = $_POST['contactname'];
$contactemail = $_POST['contactemail'];
$contactnumber = $_POST['contactnumber'];
if(!get_magic_quotes_gpc())
{
$title = addslashes($title);
$content = addslashes($content);
$contactname = addslashes($contactname);
$contactemail = addslashes($contactemail);
$contactnumber = addslashes($contactnumber);
}
// update the article in the database
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber'".
"WHERE id = '$id'";
mysql_query($query) or die('Error : ' . mysql_error());
// then remove the cached file
$cacheDir = dirname(__FILE__) . '/cache/';
$cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
#unlink($cacheFile);
// and remove the index.html too because the file list
// is changed
#unlink($cacheDir . 'index.html');
echo "<b>Job Entry: '$title' updated</b>";
// now we will display $title & content
// so strip out any slashes
$title = stripslashes($title);
$content = stripslashes($content);
$contactname = stripslashes($contactname);
$contactemail = stripslashes($contactemail);
$contactnumber = stripslashes($contactnumber);
}
include 'library/closedb.php';
?>
Check out http://us2.php.net/manual/en/function.mysql-query.php
The problem is that you are using too many single quotes here:
"WHERE id = '{$_GET['id']}'";
and your query is not acting as expected. use mysql_real_escape_string() instead.
Try this:
$query = "SELECT id, title, content, contactname, contactemail, contactnumber ".
"FROM vacancies ".
"WHERE id = '".$_GET['id']."'";
I always try to leave the variables out of my strings, just add them in with periods, I find it eliminates a lot of confusion.
One problem:
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber'".
"WHERE id = '$id'";
results in no space between the last column and the WHERE clause. Change it to:
$query = "UPDATE vacancies
SET title = '$title', content = '$content', contactname = '$contactname', contactemail = '$contactemail', contactnumber = '$contactnumber' ".
"WHERE id = '$id'";
or my preferred format:
$query = <<<END
UPDATE vacancies
SET title = '$title',
content = '$content',
contactname = '$contactname',
contactemail = '$contactemail',
contactnumber = '$contactnumber'
WHERE id = '$id'
END;
Note: You should really escape the fields using mysql_real_escape_string().
Remove the quotes around
{$_GET['id']}
and
$id
in all your queries.
Your id is of type integer I assume, which can't take a quoted version or it tries to match the integer key to the string "1"
--
Change this line
$result = mysql_query($query) or die('Error : ' . mysql_error());
to
$result = mysql_query($query) or die('Error : ' . mysql_error() . "\n\n" . $query);
Then you can see exactly what query is going into the DB. Which you can then post here for us to see.
Also please post a
describe <tablename>;
Related
I am trying to save a string with number and math operator into database. I want to save the face value of string, but php or mysql is calculating the string and then saving it to the database.
For example:
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value =".$stringValue;
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
After running the code, I want the value saved in database to be "24/2", but it is being saved as 12.
As #Uueerdo said you need to add ' sign before and after string in SQL.
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value ='".$stringValue."'";
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
Also you probably should use prepared statements (not much longer, but more safer).
$stringValue = "24/2";
$name = "xyz";
$query = "UPDATE winter";
$query .= " SET value=?";
$query .= " WHERE name=?";
$stmt = $connection->prepare( $query );
$stmt->bind_param( 'ss', $stringValue, $name );
$stmt->execute();
$res = $stmt->get_result();
I am trying to insert data into table_1 and then insert on second table if the new inserted ID not available on 2nd table if available then update it. Bellow is my code please tell me what I'm doing wrong.
<?php
$name='Name';
$pass='Passsword';
$rid='FR200000';
$sql = "INSERT INTO table_1 (id,name,pass) VALUES('".$rid."','".$name."','".$pass."')";
$res = mysql_query($sql);
if(!$res){
echo'Failed to insert';
}else{
$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
$res = mysql_query($sql);
$get_id = mysql_fetch_assoc($res);
if (!$get_id==$rid){
$site_url = 'www.example.com';
$site_email ='example#mysite.com';
$sql = "INSERT INTO site_settings (id,site_url,site_email) VALUES('".$rid."','".$site_url."','".$site_email."')";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
if ($get_id==$rid){
$sql = "UPDATE site_settings SET site_url = '" . $site_url . "', site_email = '" . $site_email . "' WHERE ID = '".$rid."'";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
?>
mysql_query()
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset
$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
$get_id = mysql_query($sql);
You will not compare directly result set with $rid
if (!$get_id==$rid){
You need to fetch data first
$row = mysql_fetch_assoc($res);
$get_id=$row['id'];// fetch data
Then compare
if (!$get_id==$rid){
// YOUR code
NOTE:- mysql is deprecated instead use mysqli OR PDO
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
create a mysql record if it doesnt exist, else update it
I have created a bit of PHP that gets data from a CSV and updates a Database Table to match the CSV's data.
My next task is, To check if the record exists, based on the unique column (sku). If it does exist update the database table dependant on the change.
Otherwise if that SKU column doesnt match do the INSERT.
The code I've got at the moment runs, However the issue I have is that if a new item is created it seems to run the update through the already existing records.
My code can be found on Pastebin
Or also here...
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect' . mysql_error());
}
mysql_select_db("db_lemonstand", $con);
class csvIterator extends LimitIterator
{
public function __construct($path)
{
$csv = new SplFileObject($path);
$csv->setFlags(SplFileObject::READ_CSV);
parent::__construct($csv, 1);
}
}
foreach (new csvIterator('data/catalogue.csv') as $entry) {
$name = $entry[23];
/* Replace Strings To Make URL Name */
$search_array = array(" ", "/", "+");
$replace_array = array("-");
$url_name = strtolower($name);
$url_name = str_replace($search_array, $replace_array, $url_name);
$long_desc = $entry[9];
$short_desc = $entry[23];
$manufacturer = $entry[11];
$price = $entry[15];
$sku = $entry[2];
$weight = $entry[29];
$width = $entry[30];
$height = $entry[5];
$enabled = '1';
$created_at = date('Y-m-d H:i:s');
$product_type_id = '1';
$tax_class_id = '1';
echo '<pre>';
print_r($entry);
echo '</pre>';
// Check see if products' SLU already exists or not
$product_exists = "SELECT sku FROM shop_products WHERE sku = '$sku'";
$result = mysql_query($product_exists, $con);
$exists = mysql_num_rows($result);
if($exists == 0 )
{
$insert = "INSERT INTO shop_products (name, description, short_description, url_name, price, sku, weight, width, height, enabled, created_at, tax_class_id, product_type_id) VALUES ('$name', '$long_desc', '$short_desc', '$url_name', '$price', '$sku', '$weight', '$width', '$height', '$enabled', '$created_at', '$tax_class_id', '$product_type_id')";
$insert_data = mysql_query($insert, $con);
}
else
{
$update = "UPDATE shop_products SET name = '$name', description = '$long_desc', short_description = '$short_desc', url_name = '$url_name', price = '$price', sku = '$sku', weight = '$weight', height = '$height', enabled = '$enabled', created_at = '$created_at', tax_class_id = '$tax_class_id', product_type_id = '$product_type_id'";
$update_data = mysql_query($update, $con);
if (!mysql_query($update,$con))
{
die('Error: ' . mysql_error());
}
}
}
You can use
INSERT INTO mytable on DUPLICATE KEY UPDATE...
You must set unique key for your table (one or more fields) and than you can use this ability.
In my example I have unique key (template, date)
$sql = 'INSERT INTO myTable
(`template`,`date`,`count`) VALUES
("' . $template . '","' . $curDate . '", 1)
ON DUPLICATE KEY UPDATE count = count + 1';
Store store you fields in a var as $fields or anything else that you want and execute this query for that you need a single field as reference that's why i included $Id
INSERT INTO table_name SET id = '$Id', $fields ON DUPLICATE KEY UPDATE $fields
I have two tables, one is 'tags' that stores "tid" (auto increment) and "name" (name of tag). The second table "tags_data" stores the data on each tag. This table has the fields "tid" (from the first table) and a few others.
This is so people can tag content on my website. When I tag content I want to first check if that tag already exists in the first table. If it doesnt exist then we insert the tag into the DB and use the tid to insert into the second table. I have this part working so far.
The problem is when the tag already exists in the DB, I want to grab the existing tid and use it in my second query.
This is the code I have so far:
// check if tag already exists
$tagexists = "SELECT COUNT(*) as cnt FROM tags WHERE 'name' = '$usetag' LIMIT 1";
$results = mysql_query($tagexists) or die('Invalid query: ' . mysql_error());
if ($results['cnt'] == 0) {
// tag is not yet in DB
$tagquery1 = "INSERT INTO tags (name) VALUES ('$usetag')";
$result = mysql_query($tagquery1) or die('Invalid query: ' . mysql_error());
$lastid = mysql_insert_id();
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
} else {
// tag is already in DB, grab the tid
$grabtid = "SELECT tid FROM tags WHERE 'name' = '$usetag' LIMIT 1";
$results = mysql_query($grabtid) or die('Invalid query: ' . mysql_error());
$row = mysql_fetch_array($results);
$lastid = $row['tid'];
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
}
There is something wrong with the way I am checking if a tag exists already. I was following a guide online using COUNT but it doesnt seem to be working properly.
$results['cnt'] == 0 is wrong. You are forgetting to get the result. ($results is a resource id.)
if(mysql_result($results) == 0){
Likewise, your second part of the if that gets the existing data is missing it too. You want to use $data = mysql_fetch_assoc($result); there.
I think your code is wrong
$tagexists = "SELECT COUNT(*) as cnt FROM tags WHERE 'name' = '$usetag' ";
$res = mysql_query($tagexists) or die('Invalid query: ' . mysql_error());
$results = mysql_fetch_assoc($res);
if ($results['cnt'] == 0) {
// tag is not yet in DB
$tagquery1 = "INSERT INTO tags (name) VALUES ('$usetag')";
$result = mysql_query($tagquery1) or die('Invalid query: ' . mysql_error());
$lastid = mysql_insert_id();
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
} else {
// tag is already in DB, grab the tid
$grabtid = "SELECT tid FROM tags WHERE 'name' = '$usetag' LIMIT 1";
$results = mysql_query($grabtid) or die('Invalid query: ' . mysql_error());
$row = mysql_fetch_array($results);
$lastid = $row['tid'];
$tagquery2 = "INSERT INTO tags_data (tid, nid, uid) VALUES ($lastid, $nid2, $uid)";
$result = mysql_query($tagquery2) or die('Invalid query: ' . mysql_error());
}
I am trying to use a value that I receive from a MySQL query and then do an insert but it's not working. I'm getting an syntax error but the Insert Query is correct.
The select query returns an amount which I'm checking and then the program should do the insert query.
<?php
require 'header.php';
$resID = mysql_real_escape_string($_POST['resID']);
$materialen_id = mysql_real_escape_string($_POST['materialen_id']);
$aantal = mysql_real_escape_string($_POST['aantal']);
$effectief_gebruikt = mysql_real_escape_string($_POST['effectief_gebruikt']);
$opmerking = mysql_real_escape_string($_POST['opmerking']);
//$datum_van = date('d-m-Y', $_POST['datum_van']);
//$datum_tot = date('d-m-Y', $_POST['datum_tot']);
$datum_van = $_POST['datum_van'];
$datum_tot = $_POST['datum_tot'];
$sql = "SELECT `aantal_beschikbaar`
FROM `materialen`
WHERE `id` = $materialen_id";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$tot = $row['aantal_beschikbaar'];
echo 'totaal: ' . $tot;
}
$sql2 = "SELECT `aantal` FROM `materialen_per_reservatie`
WHERE `materialen_id` = $materialen_id";
$result2 = mysql_query($sql2) or die(mysql_error());
while ($row = mysql_fetch_array($result2))
{
//$aant = $row['aantal'];
//echo $aant
echo $row['aantal'];
}
$besch = ($tot - $aant);
echo 'beschikbaar: ' . $besch;
/*$sql3 = "SELECT * FROM `materialen_per_reservatie`
WHERE `reservaties_id` = $resID
AND `materialen_id` = $materialen_id";
$result3 = mysql_query($sql3) or die(mysql_error());*/
if($besch > $aantal){
$string2 = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
mysql_query($string2) or die(mysql_error());
}
require 'footer.php';
?>
Provided that the error is on only the insert query...
Your insert query is missing a needed space:
INSERT INTO `materialen_per_reservatie` (`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')
Add a space after materialen_per_reservatie. And I'm not sure you need all of the quotes.
INSERT INTO materialen_per_reservatie (reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')