Error while inserting data into Mysql database - php

I am trying to insert data into Mysql table, but it is giving me an error as-
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 'Scoretab VALUES ('UX 345','22','0.8562675')' at line 1
This is the php-mysql snippet that im using :
if($value >= 0.70){
$mu_id = $ros['c_id'];
$moc_id = $ram['t_id'];
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
$op1 = mysql_query($query) or die(mysql_error());
}
This is my table structure:
CREATE TABLE IF NOT EXISTS `Scoretab` (
`mu_id` varchar(10) NOT NULL,
`moc_id` int(5) NOT NULL,
`score` decimal(5,4) NOT NULL,
UNIQUE KEY `mu_id` (`mu_id`)
)

There could potentially be a few problems with this query
$query="INSERT INTO Scoretab VALUES ('$mu_id','$moc_id','$value')";
Does the number of columns match the fields your trying to insert? Have you tried using using specific column identifier Scoretab (col,col,col) values (val, val, val)
Does any of your values contain an unescaped apostrophe? You might want to consider using mysql_real_escape_string for $mu_id and intval for $moc_id maybe!
$value is a float you don't need to ad apostrophes while inserting
Are you sure you are connected to the same database you have this table in?
this could be a possible working solution (edit)
if ($value >= 0.70)
{
$mu_id = mysql_real_escape_string($ros['c_id']);
$moc_id = intval($ram['t_id']);
$query = "INSERT INTO `Scoretab` VALUES ('$mu_id', $moc_id, $value)";
$op1 = mysql_query($query) or die(mysql_error());
}

try this
$query="INSERT INTO Scoretab (mu_id,moc_id,score) VALUES ('$mu_id','$moc_id','$value')";

The error seems to be before the table name Scoretab. Did you check your syntax carefully?
Sometimes we don't see what's right in front of our eyes! :D
Just replicated the example and everything worked for me.

Related

updating the mysql table if query store_num exits

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.

PHP set a default value for database insert

I have a number box <input type='number' step='any' name='number' id='number'>
and I take that value and call it in a function like so:
insertIntoDB($number)
function insertIntoDB($number = null){
//insert into db
"INSERT INTO 'tablename' (number) VALUES " . $number;
}
and I get 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 ' '
Is there away so if the user leaves the field blank it will enter the value as null?
You can set default values when creating the table itself, but apart from that, the code you pasted is missing some brackets:
INSERT INTO `tablename` (number) VALUES (" . $number.")";
If you want to use a NULL when inserting and get a default value in the table, you can do it when creating the table like this:
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
someField VARCHAR(15) NOT NULL DEFAULT 'on'
)
Now when you try to insert data into it, you can do the following:
insert into `tablename` (id, someField) values (null, null)
and get a row with an incremented ID and the string 'on' in the column someField.
If you want to check for nulls when inserting data into a table, you can then use something like the following to ensure you have the value:
$someField=(isset($number))?$number:'null';
INSERT INTO `tablename` (number) VALUES (" . $someField.")";
This is assuming you have already verified that $number is either numeric or isn't submitted when sending the form.

Can only insert into mysql table once

I have an issue where I can only insert data into my table once. If i delete the row and insert a new one, it works but if I already have a row and try to insert another one, it doesn't work. No errors in the console or network.
I'm inserting with this:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = mysql_real_escape_string($_POST['name']);
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($sql, $con)
or die("Error: ".mysql_error());
mysql_close($con);
?>
I'm thinking it might have to do with how my table is set up, primary key and such. I have an id column which is the primary and I think it's auto-increment, can't tell.
Since you are not sure about whether the id field is auto-increment or not, you should alter your table like this,
ALTER TABLE `yourtable`
MODIFY COLUMN `id` int(11) NULL AUTO_INCREMENT FIRST;
the result FROM SHOW CREATE TABLE tableName would help.
I would guess you have a unique index on on of your fields and you are trying to insert a second record with the same value.
Also CHECK TABLE tablename could help identify the problem.
I had this... I had set my first column as 'unique' and my 'Insert' didn't involve that column.
As a result the 'Insert' added a value of zero into the 'Unique' column (I'd set that column to 'integer').
When I did another insert 'I THINK' that the 'Insert' wanted to add another zero in the 'Unique' column that I wasn't 'Inserting' into, so it tried to 'Insert' another zero, BUT because that column was 'unique' it wouldn't allow another zero and refused the 'Insert'.
I proved this by changing the first 'Inserts' entry into the 'Unique' column manually to another 'Integer' then the 'Insert; statement worked one more time.... repeat process above as described and my table allowed another 'Insert'.
Hope this makes sense and helps?.
I had a similar problem, however mine was where I was using the INT data type in my create table script for storing a 13-digit long number, and it only wanted to accept something 10-digits in size. Changing this to a VARCHAR(13) fixed the problem for me.

Syntax error with IF EXISTS UPDATE ELSE INSERT

I'm using MySQL 5.1 hosted at my ISP. This is my query
mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
BEGIN
UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
END ELSE BEGIN
INSERT INTO licensing_active(title_1) VALUES('$title_1')
END
") or die(mysql_error());
The error is
... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1
My actual task involves
WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...
but I have reduced it down to make things simpler for my problem solving
In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.
Here is a simple and easy solution, try it.
$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}
Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.
This should do the trick for you:
insert into
licensing_active (title_1, time)
VALUES('$title_1', '$time')
on duplicate key
update set time='$time'
This is assuming that title_1 is a unique column (enforced by the database) in your table.
The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.
The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
Another solution
$insertQuery = "INSERT INTO licensing_active (title_1) VALUES ('$title_1')";
if(!$link->query($insertQuery)){ // Insert fails, so update
$updateQuery = "UPDATE licensing_active SET time='$time' WHERE title_1='$title_1'";
$link->query($updateQuery);
}
Here is the example I tried and its works fine:
INSERT INTO user(id, name, address) VALUES(2, "Fadl", "essttt") ON DUPLICATE KEY UPDATE name = "kahn ajab", address = "Address is test"
I am amazed to see so many useless codes and answers...
Just replace INSERT with REPLACE.
¯\(ツ)/¯

mysql muliple queries in one statement

I've looked around on stackoverflow for a similar question, but haven't found exactly what I was looking for, so here goes. In phpMyAdmin you can have multiple queries in one statement and it executes it for you, eg:'
UPDATE `test` WHERE `test2` = 4;
UPDATE `test` WHERE `test4` = 8;
UPDATE `test` WHERE `test8` = 1;
Now if I try to do something like that in PHP, it doesn't work at all. eg:
$test = 'UPDATE `test` SET `value` = "123" WHERE `test2` = 4;
UPDATE `test` SET `value` = "321" WHERE `test4` = 8;
UPDATE `test` SET `value` = "533" WHERE `test8` = 1;';
mysql_query($test);
Gives and 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 '; UPDATE
test SET value = "123" WHERE test2
= 4; UPDATE test SE' at line 1
Is it even possible to combine, say, multiple queries like above, in one statement? I want to do this in the following situation: (The logic behind this is probably very bad, but I don't have much MySQL experience, so please let me know if there's a better way to do it)
The following loops over a couple of times:
function SaveConfig($name, $value)
{
global $sql_save_query;
$sql = 'SELECT * FROM `config` WHERE `name` = "'.$name.'"';
$res = mysql_query($sql);
if($res)
{
$sql_save_query .= 'UPDATE `config` SET value = "'.$value.'" WHERE `name` = "' .$name. '"; '."\n";
}
else
{
$sql_save_query .= 'INSERT INTO `config`(`id`,`name`,`value`) VALUES("","' .$name. '","' .$value. '"); '."\n";
}
}
Then after the loop finishes it runs:
mysql_query($sql_save_query);
Which gives an 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 '; UPDATE
config SET value = "" WHERE name =
"fcolour2"; UPDATE config SE' at
line 1
Now my other option (in my mind) is to just execute an SQL query after each loop, one query at a time. But wouldn't that be bad/slow/bad practice?
the php API forbids you to issue multiple queries in a single call to reduce the chance of an SQL injection attack to your code (think of what would happen if I passed '; UPDATE users SET admin=1 WHERE username='hacker' to your login script as username). You need to either execute multiple statements, or wrap the logic of your statements into a single statement (which is not possible in your case).
It's not possible to execute multiple queries using mysql_query.
You can perform multiple inserts at once using this syntax:
INSERT INTO table (col1, col2) VALUES (0, 1), (2, 3), (4, 5); -- Insert 3 rows
In general less queries = better but for updates you just have to do them.
The loop you have in your example is indicative of an architectural problem.
If you are dealing with an existing record, pass the primary key - then you don't need the select at all - you can just run an update statement.
If you are dealing with a new record, pass no key - then you know to run an insert statement.
probably you can use INSERT ... ON DUPLICATE KEY UPDATE
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Some other useful links
http://dev.mysql.com/doc/refman/5.0/en/replace.html
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/
$sqls = explode(";",$test);
foreach ($sqls as $key=>$sql) {
if (strlen(trim($sql))>0) {
mysql_query(trim($sql));
}
}

Categories