Everyone!
I am working on application using php and mysql. Basically, initially, I am inserting the new data entries using html form into the database where store# is my primary key. For now I can not update the existing store# (as its my primary key) and get a message saying "Duplicate entry for store 967 (example)".
I want to update the "store" table if entery exists. Here is my code posted below, but I am getting another error message
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 '['967'],address=['500 kipling avenue 1'],dsm_name=['n/a'],phone=['416-967-' at line 1
I am not sure if I am using the if conditional at right spot.
**$sql = "INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
$mysqli_query = "SELECT * from 'stores' WHERE $store = 'store_num'";
if ($mysqli_query == TRUE){
$sql = "UPDATE `stores` SET `store_num`=['$store'],`address`=['$address'],`dsm_name`=['$dsm'],`phone`=['$phone'],`router_type`=['$router'],`high_speed_pri`=['$highspeedpr'],`dsl_log`=['$dsllog'],`dsl_pass`=['$dslpas'],`secondary_conn`=['$secondary_conn'],`sec_dsl`=['$secdsl'],`sec_pass`=['$sec_pass'] WHERE 1";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>**
Replace instead of Insert
Since your update statement includes all the same fields as Insert, you can simply use a REPLACE Statement. As stated on the linked documentation:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See
Section 13.2.5, “INSERT Syntax”.
So, changing the code to the following should work:
$sql = "REPLACE INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
Error Reason
Your problem is with the syntax in the update statement. What is store_num, is it a number or a string?
You should change your syntax to not include the square brackets in the actual mysql query.
If $Store is Number:
=['$store'], to =$store
If $Store is Text:
=['$store'], to ='$store'
Final Recommendation
Even better though will be use prepared statements which are also secure and avoid against SQL injection attacks.
You can do this logic with a single query, using on duplicate key update. First, you have to define store_num as a unique key, if it is not already a unique or primary key:
CREATE UNIQUE INDEX idx_stored_storenum on stores(store_num);
Then use this insert:
INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`,
`dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`
)
VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr',
'$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')
ON DUPLICATE KEY UPDATE address = values (address),
dsm_name = values(dsm_name),
. . .
sec_pass = values(sec_pass);
Your particular problem is the square braces, which MySQL doesn't recognize.
Related
I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.
I have created a table with an AUTO INCREMENT column (Id, primary key), and have done the following php code:
$med="MED0x";
$sql=" INSERT INTO Inscricoes2 (`Nome`,`Nome Clinico`, `Numero Cedula`, `Email`, `Descricao`) VALUES ('$nome_completo', '$nome_clinico', '$numero_cedula', '$email' , '$comentario') " ;
$num=mysql_insert_id($con);
$resultado=$med . $num;
echo "$resultado";
But it doesnt echo anything, and an error appears. What is wrong here?
That is because you are never executing the query, hence there is no insert id.
mysql_query($query);
$num=mysql_insert_id($con);
How can I prevent SQL injection in PHP?
I'm making a search engine based on the API of Faroo.com (http://www.faroo.com/hp/api/api.html) for a school project. I would like to index the index of Faroo, so that users (in my situation, children) can vote up or vote down individual results.
What my (PHP)-script is like:
Look in the MySQL-database if the query exists.
yes => load the results from the database and show them to the user
no => load the results from Faroo, show those results to the user and store them in the database
My database looks like this:
I'm getting all the data stored in the columns from the Faroo API, except for the 'id'-column.
The last part (of storing the Faroo-data in the database) is where it goes wrong:
for($x=0; $x<$tel; $x++){
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, $q, $titles[$x], $urls[$x], $domains[$x], $kwics[$x], 0);";
echo '<br />'.$x.'e query: #'.$sql.'#';
if(!$resultaat = $db->query($sql)){
die('De query kon niet worden uitgevoerd: [' . $db->error . ']');
}
$resultaat = mysqli_fetch_array($resultaat);
}
$tel is a variable which counts the number of results I get from Faroo. It gets defined before this piece of code.
When I run this code, I am getting a nice MySQL-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 'States Bureau of Mines - Wikipedia, the free encyclopedia,
www.wikipedia.org' at line 1
I've searched, and searched, but I couldn't find what the SQL-error is. I think it has something to do with the strange characters in the strings, or maybe my quotation is false?
Kind regards,
Max
I think you need to use single quotes ' for varchar columns, so change as follow
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, '$q', '$titles[$x]', '$urls[$x]', '$domains[$x]', '$kwics[$x]', 0)";
You also have an extra double quote at the end of the query which i removed, you won't need singles quotes for columns id and votes since they are integer fields
I'm getting following error when I submit a form:
Can't added a new post. Incorrect integer value: '' for column 'aid' at row 1
Php Code:
$insert = mysql_query("INSERT INTO brt_articles VALUES( '', '$post_title', '$des',
'$date', '$org_date')");
if($insert)
{
echo "<font color=green>Successfully added a new article.</font>";
header("Refresh:3; url=allbrtarticle.php");
}
else
{
echo "<font color=red>Can't added a new post</font>" .
mysql_error();
}
In my Localhost It's ok. But in server why it's giving me a error message ?
Probably that DB has differents settings than your local. STRICT_TRANS_TABLES mode might be turned on.
Try SELECT ##GLOBAL.sql_mode; and SELECT ##SESSION.sql_mode;.
The aid field does not accept '' value as input.
The safest way is to specify column names as you are sending the query.
INSERT INTO brt_articles (title_field, description_field, date_field, org_date, fieldname) VALUES('$post_title', '$des', '$date', '$org_date');
If aid is a primary key, simply omit that field in your query
INSERT INTO brt_articles VALUES('$post_title', '$des', '$date', '$org_date')
aid is a column that is an integer, and you're trying to insert '' into it. '' is not a number, so the insertion fails.
Perhaps there's a server setting to auto-convert the incorrect type, but you shouldn't rely on it (as you've just found out)
This causes the error aid(INT) - which is included on you table columns(first column).
If its auto increment remove the ''.
$insert = mysql_query("INSERT INTO brt_articles VALUES('$post_title', '$des',
'$date', '$org_date')");
Regards
try
"INSERT INTO brt_articles VALUES('".$post_title."', '".$des."', '".$date."', '".$org_date."')"
Remove first '' it's not needed as MySQL automatically add it if its primary key and auto_increment.
your local db has the value of that column set to auto increment or has a default value.
on the server db, the table definition is not the same.
review and compare the table definitions and then make them consistent.
I have a simple INSERT statement which looks like this...
mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`) VALUES ('{$_SESSION['user_id']}', ('$problemID'), ('$comment'))") or die(mysql_error());
Everything is being inserted fine apart from the $problemID variable. In the MySql table it is just returning a 0. The table is set up to receive integers up to 11 characters.
The variable itself is set on a different page but is retrieved using this...
$problemID = intval( $_GET["problem"]);
If I echo the $problemID I get the correct number so I'm unsure as to why it won't just insert this number into my table. Any pointers would be great.
Make sure that your comment is more clearly sanitized; Try something like this:
mysql_query( sprintf(
"INSERT INTO
comments (`user_id`, `profile_id`, `comment`)
VALUES
(%s, %s, '%s')",
intval( $_SESSION['user_id'] ),
intval( $problemID ),
mysql_real_escape_string( $comment )
)) or die( mysql_error() );
Just to be thorough, make sure that your table has a separate primary index (aka entry ID) with auto-increment tacked on. It could be that your MySQL insertion is working fine, however, the receiving table doesn't know that it should keep appending entries.
My hunch is that your INSERT query is referring to the wrong column in your comments table, as you have the following:
INSERT INTO comments (`user_id`, `profile_id`, `comment`)
but you're referring to a variable named $problemID, so my guess is that you meant something like this:
INSERT INTO comments (`user_id`, `problem_id`, `comment`)
Perhaps you copied and pasted the query code but forgot to change the column name in the projection?
Remove the brackets and try to add the variables rather than including them into the string.
mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`)
VALUES ('".$_SESSION['user_id']."', ".$problemID.", '".mysql_real_escape_string($comment)."')") or die(mysql_error());