Sql Error - Incorrect integer value - php

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.

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.

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.
¯\(ツ)/¯

I cannot get default in sql to work

I am having an issue with sql right now; I have gave a value a default so if the field is left empty when the user submit, but it is not working. When the user submits an empty field to leave a comment instead of it default to anon it does nothing. Also, in the datebase the field is empty.
name VARCHAR (50) default 'anon',
$name= $_POST['name'];
$title= sha1($_POST['title']);
$texts= $_POST['texts'];
$forum_id = $_POST['forum_id'];
$name = str_replace("'","''",$name);
$title = str_replace("'","''",$title);
$title = str_replace("b074acd521","STREAMER",$title);
$texts = str_replace("'","''",$texts);
$title = substr($title,0,8);
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
mysqli_query($conn1, $sql) or die('Error inserting to database.');
mysqli_close($conn1);
header('Location: requests.php');
Is there another way to do it or am I just doing something wrong?
The SQL query your using will not insert the default value from your database because you are specifying a value for name (even if that value is an empty string, or null) :
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
Instead if you want the default value to be inserted into the name field you must not specify the name column in the insert statement :
$sql = "INSERT INTO post (title, texts, forum_id) VALUES ('$title', '$texts', '$forum_id')";
In SQL query you can specify for which fields, values will be provided in the query and remaining fields from the table would contain default value (in case of AUTO_INCREMENT, the next integer value will be used).
Where you given the default value directly applied in SQL? the value left in DB ultimately is what exactly you passed to DB server by SQL way, or just you defined a variable where if it don't accept a value from user then use the default value instead, please try to debug this to insure the value was handled correctly.
while insert the values you shouldn't give the column which you set default value
below Example explain it...Try like this...
create table er(id int,name char(10),gender char(2)default 'M')
Here i took gender as default
now i insert the values
insert into er (id,name)values(1,'poda')
select * from er

Error: Column count doesn't match value count at row 1

I am getting this error here is my code
if(isset($_POST['submit']))
{
$projTit=mysql_escape_string($_POST['projecttitle']);
$projCat=mysql_escape_string($_POST['projectcategory']);
$budget=intval(mysql_escape_string($_POST['budget']));
$description=mysql_escape_string($_POST['editor1']);
$query=sprintf("insert into projects value('%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
if (!mysql_query($query)){
die('Error: ' . mysql_error());
}
echo '<p class="record">Your Record has been Added<p>';
}
?>
I have tried to write %d in '' but still not working.
Your table has five columns. However, you are not providing a value for the Project_Id column. This gives you the error you mentioned.
I understand that you're not providing a value since it's likely a PRIMARY KEY that autoincrements. To tell MySQL that you are intentionally not passing a value for that column, you should add NULL as the first value.
value(NULL, '%s','%s','%s',%d)
However, you really should specifically name which columns you are inserting into in case you add a new column at a future date.
INSERT INTO projects (col1, col2, col3, col4) value ('%s','%s','%s',%d)
You should really specify the column names or your app will break if you add a column later, even if it has a useable default value:
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
(...)
Especially since you have an auto_increment ID column it makes sense; otherwise you'd always have to specify it as NULL in your query.
The easiest (but also ugliest) fix would thus be:
$query=sprintf("insert into projects value (null, '%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
The good fix would be this:
$query = sprintf("
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
('%s', '%s', '%s', %d)
", $projTit,$description,$projCat,$budget);
By the way, consider using PDO - then you can use something similar to a format string but don't have to deal with escaping.
try naming the columns you want to fill like
insert into projects (col1, col2, col3) values (...)

Categories