MySql INSERT statement is inserting a '0' rather than variable contents - php

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());

Related

How to make PHP MYSQL Insert query only with values which are existed for certain columns?

I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}

How to replace some values if a user already exists?

I don't know how to replace some data if a "user" already exists.
I've tried ON DUPLICATE KEY UPDATE but I came to realize that this will probably not work. Because the only value that isn't updated is 'user' in my code but the other 3 values are constantly updated every 5 minutes.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES ('$Name'), world = VALUES ('$World'), status = VALUES ('$status')
The idea is if, for example, user "bob" already exists update his other 3 values bot, world, status, instead of creating a new line and so on.
Edit: this is how I have it setup in Mysql
The argument to VALUES() should be the name of a column, not a string. You put the name of the column that you would have inserted into.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES (bot), world = VALUES (world), status = VALUES (status)

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.

Insert...on duplicate key update- repeatedly inserting

In my Document table I have:
id (auto int index),
user_id (P.key and links to other table),
Doc_Name,
abstract
When I use the code below, it just inserts another row so I have two user_id's the same when it should have updated. Obviously the id just carries on in number as it is auto int and I'm not sure if this has something do with why it won't work.
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`)
VALUES ('%d','%s','%s')",'$user_id', '$Doc_Name', '$abstract')
ON DUPLICATE KEY UPDATE
user_id=user_id+'$user_id',
Doc_Name=Doc_Name+'$Doc_Name',
abstract=abstract+'$abstract' "
);
Cargo cult programming? Using sprintf() without any % placeholders is just.... WRONG. As well, why the addition on the updated fields?
MySQL uses concat() for concatenation. + is purely a mathematical operation. Doing 'a' + 'a' does NOT give you aa, you'll get 0.
if user_id is unique field in your table, your query should look like this:
$query = sprintf("
INSERT INTO
`document`(`user_id`, `Doc_Name`, `abstract`)
VALUES
('%s', '%s', '%s')
ON DUPLICATE KEY UPDATE
`Doc_Name` = VALUES(`Doc_Name`),
`abstract` = VALUES(`abstract`)
", $user_id, $Doc_Name, $abstract);

php = insert working but want to check if in db already based on one field

Have a working system where I am posting news articles. I sometimes add the same one twice and want to avoid this. So how can I alter my insert statement to first check for a match on the field named 'title' to see if it is equal to the title I have in the record I am trying to submit?
Here is php code I use, as it was done for me since I am a PHP novice but I do not know how to check for the title=title and then not add it if it finds it or to add it if it doesnt find a match:
$result = mysql_query("
insert into news (
catalogid,
title,
intro,
content,
viewnum,
adddate,
rating,
ratenum,
source,
sourceurl,
isdisplay,
isfeature,
subip,
vsent,
timesubmitted)
values
('1',
'$title',
'$intro',
'$content',
'0',
'$subdate',
'$source',
'$icheck',
'N/A',
'$sourceurl',
'$isapp',
'0',
'127.0.0.1',
'0',
'$tsdate')"
);
Thank you!
There are database-specific tricks like on duplicate key update, but typically you simply test for the existence of a record with the same key via a select. If the record exists, you update it with the new data, otherwise you insert a new record.
You can run a check query before inserting , like:
$sql = mysql_query("SELECT catalogid from news WHERE title='".$yourTitle."'");
if(mysql_num_rows($sql) < 1) {
//add your insert query here
}
Hope that helps
$result = mysql_query("SELECT * FROM news WHERE `title`=$title");
if (!$result)
{
// your code INSERT
$result = mysql_query("
insert into news (
catalogid,
title,
intro,
content,
viewnum,
adddate,
rating,
ratenum,
source,
sourceurl,
isdisplay,
isfeature,
subip,
vsent,
timesubmitted)
values
('1',
'$title',
'$intro',
'$content',
'0',
'$subdate',
'$source',
'$icheck',
'N/A',
'$sourceurl',
'$isapp',
'0',
'127.0.0.1',
'0',
'$tsdate')"
);
}
You can't do this with a single INSERT statement, at least not directly. If you set the title field in your database table to UNIQUE, you can prevent MySQL from inserting a record with a duplicate title. You will need to detect if the mysql_query function returns FALSE; if it does, you know a duplicate record was inserted and you can handle this however you see fit.

Categories