PHP - MySQLi INSERT not working - php

I must to send an INSERT query to MySQL database, assuming all the variables are correctly setted, I'm using this code:
$check_alrd_sent = $mysqli -> query("SELECT * FROM reviews WHERE id_prod =" . $id_prod . " AND id_user = " . $current_usr . " LIMIT 1");
$check = mysqli_fetch_all($check_alrd_sent);
if ($check != NULL) {
$check_err = 1;
} else {
$ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , " . $id_prod .", " . $current_usr . ", " . $review . ", " . $rating . ");");
$ins_result = 1;
}
mysqli_free_result($check_alrd_sent);
The $ins_result variable is correcly set as result, as I can see using var_dump() but now rows are insert in database.
The strange thing is that if I call the MySQL error log can clearly see that the insert is sent to the database correctly as:
42 Query INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , 11, 1, asd, 4)
But it doesn't appear in the table.
Any suggestions? Thanks

You have two issues in your INSERT Statement:
Value of review column is a string so you need to use quotes around review VALUE.
I think ID is an AUTO INCREMENT NOT NULL field. So no need to use in INSERT Query.
Modified query:
INSERT INTO `reviews`
( `ID_prod`, `ID_user` ,`review` ,`stars`)
VALUES (11, 1, "asd", 4)

varchar fields must be in 2 quota, so review field must be in 2 ':
$ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user`
,`review` ,`stars`) VALUES (NULL , '" . $id_prod ."', ' " . $current_usr . "', '" .
$review . "', '" . $rating . "');");

In your output, "asd" is not in single quotes. That would be invalid SQL. Should also think about converting to non-deprecated SQL functions such as PDO.

Related

PHP pg_query update statement

I am trying to updata a database table using pq_query in PHP. I have the following code:
$q = "UPDATE tableName SET ('data1 = " . $data1 . "', data2='" . $data2 . "') WHERE user=".$user;
$success = pg_query($q);
if (!$success) {
$errormessage = pg_last_error();
echo "Error " . $errormessage;
}
I am getting the following error message:
ERROR: syntax error at or near "'data1 = '"
LINE 1: UPDATE tableName SET ('data1 = 10', data2= 20'') WHERE user=
Replace your query with this query
$q = "UPDATE tableName SET data1 = '$data1', data2='$data2' WHERE user='$user'";
Explaination: You should pass variable in single quotes('') if your query in double quotes.
You are using a lot of quotes which it is not understood by PostgreSQL, try simply this :
$q = "UPDATE tableName SET data1 = " . $data1 . ", data2=" . $data2 . " WHERE user=".$user;
Remove those single quotes !

SQLite Auto increment field via PHP

I have this current SQLite table:
CREATE TABLE Goal (
id INTEGER PRIMARY KEY,
Name CHAR(32) NOT NULL,
Image CHAR(256),
Target INTEGER NOT NULL,
Priority CHAR(32) NOT NULL
);
And am trying to create an integer id via PHP as follows:
$query = 'INSERT OR IGNORE INTO Goal (Name, Image, Target, Priority) VALUES'; // Query to insert goal-related info into Goal table
$query .= "('" . $name . "', '" . $image . "', '" . $target . "', '" . $priority . "');";
$addGoalDB -> makeQuery( $query );
$query = 'SELECT last_insert_rowid()';
$result = $addGoalDB -> makeQuery( $query );
$id = $result -> fetchArray(SQLITE3_ASSOC);
$id = $id['id'];
$query = 'INSERT OR IGNORE INTO Users_Goal (Email, id) VALUES';
$query .= "('" . $_SESSION['username'] . "', '" . $id . "');";
$addGoalDB -> makeQuery( $query );
But keep getting an undefined index error with
$id = $id['id'];
I am assuming the query is wrong but cannot find where my problem is. This link: http://alvinalexander.com/android/sqlite-autoincrement-insert-value-primary-key makes it look straightforward but does not work with my code. I would greatly appreciate any help with this.
You are trying to read a column named "id". But columns are named after what you have written in the SELECT clause, so the actual column name is something like last_insert_rowid().
Give the column a proper name:
$query = 'SELECT last_insert_rowid() AS id';

mysql replace into with SET-syntax overrides all fields

I have the following query:
REPLACE INTO `oxarticles`
SET
OXID = '10-1010',
oxartnum = '10-1010',
oxtitle = 'Dummy',
oxprice = '10.000000',
oxstock = '100',
importstatus = 1"
This works so far as expected, but the fields I do not specifiy, are just overwritten with ' ' / empty string. From what I read, should this syntax work identically like the UPDATE-command.
Am I missing something? How can I prevent that fields are replaced with '' ?
Edit 1
Just to clarify, I can't just use UPDATE. I am setting a flag (importstatus) to 0 before every run and during the import to 1. After the import finishes, I delete all articles, which are still on status 0.
// Just for the compeletion, here is the PHP-snippet:
while (!feof($this->handle))
{
$row = fgetcsv($this->handle, 0, ";");
$sSql = "REPLACE INTO oxarticles SET "
. " OXID = '" . $row[0] . "', "
. " oxartnum = '" . $row[0] . "', "
. " oxtitle = '" . $row[1] . "', "
. " oxprice = '" . str_replace(",", ".", $row[4]) . "', "
. " oxstock = '" . str_replace(",", ".", $row[5]) . "', "
. " importstatus = 1";
// $sSql = "UPDATE oxarticles SET oxtitle ='" . $row[1] . "', oxprice='" . $row[4] . "', oxstock='" . $row[5] . "' WHERE oxartnum ='".$row[0]."'";
$this->db->execute($sSql);
}
From the mysql 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”.
In other words, the row is being deleted and then inserted, hence your old values aren't staying intact. Perhaps you could select the original row first, and feed those values back in where appropriate.
You query will replace old data into new data if you do not provide data for a field it will set to null . If you do not want to loose your data just want to update field use on duplicate key update.
If did't found any match it will insert new row
If found it will replace data if provide
INSERT INTO table (id,a,b,c,d,e,f,g) VALUES (1,2,3,4,5,6,7,8) ON
DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

Check if a primary key exists

I think this has already been asked, but none of the answers made sense to me. My code is...
if ($current_string == "") {
$new_entry_query = 'INSERT INTO house (id, string) VALUES ("' . $userid . '", "' . $new_home_entry . '")';
mysql_query($new_entry_query);
Header('Location: landing.php?pho=');
} else {
$entry_update_string = $current_string . $new_home_entry;
$new_entry_query = 'UPDATE house SET string="' . $entry_update_string . '" WHERE id="' . $userid . '";';
mysql_query($new_entry_query);
Header('Location: landing.php?pho=');
}
My table has two columns. "id", which is primary, and "string" which is not. If you notice, in the first if-statement I'm checking if the query for "string" came up empty, when I asked the database to check at my "id."
I've run into a problem. There is another function on my site which deletes everything from the "string" column. If that function runs, then I run this script I will end up getting an error.
I need to check if the "id" is already there, so that I know if I should create an entirely new row, or just append "string." How would I do that? Thanks.
You should use one query:
INSERT INTO house (`id`, `string`)
VALUES ("' . $userid . '", "' . $new_home_entry . '")
ON DUPLICATE KEY UPDATE `string` = VALUES(`string`)

Trying to extract 5 characters from a column when adding record mysql via php

My part_no column has the following format: 000-00000-00 for all records.
I need to extract the five middle characters from part_no and place it in the core column when I create the record.
I can't get my script to work.
I'm not getting any errors. Just not working.
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes)
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
$query2 = "select part_no from cartons_current";
$sel = mysql_query($query2);
$res = mysql_result($sel);
while($row = mysql_fetch_row($res)) {
$core_digits = split('-',$row[0]);
$core =$core_digits[1];
$query3 = "insert into cartons_current(core) values($core)";
$sel2 = mysql_query($query3);
}
You can update your cartons_current table based on your cartons_added table with something like:
INSERT INTO cartons_current(core)
SELECT SUBSTR(part_no, 5, 5) FROM cartons_added
You will probably want to limit that with a WHERE clause or maybe deal with what happens when this value is already in cartons_current (use either INSERT IGNORE or ON DUPLICATE KEY UPDATE)
You are right, the script has no error.
I think the problem is on your SQL that made you can't insert a new row, specifically on the table structure. Maybe you defined a PRIMARY KEY without AUTO_INCREMENT, defined a INDEX or UNIQUE key that is not the core key or there have some other key that did not have default value. Remember that you can't insert a row without defining all required field.
You script is selecting all part_no and for every part_no you are inserting a new row in the same table, so maybe there is the problem.
I think what you want is update every result to add they core value, you can do that with UPDATE as this code:
function getValue($value) {
return "'" . trim(mysql_real_escape_string($value)) . "'";
}
mysql_query('INSERT INTO `cartons_added` (`add_time`, `type`, `part_no`, `add_type`, `add_qty`, `add_ref`, `add_by`, `add_notes`)
VALUES (' .
getValue($date) . ', ' .
getValue($_POST[type]) . ', ' .
getValue($_POST[part_no]) . ', ' .
getValue($_POST[add_type]) . ', ' .
getValue($_POST[add_qty]) . ', ' .
getValue($_POST[add_ref]) . ', ' .
getValue($_POST[add_by]) . ', ' .
getValue($_POST[add_notes]) .
')');
$partNoQuery = mysql_query('SELECT `part_no` FROM `cartons_current`');
while($partNoResult = mysql_fetch_assoc($partNoQuery)) {
list($prefix, $core, $suffix) = explode('-', $partNoResult['part_no']);
mysql_query('UPDATE cartons_current SET `core` = \'' . $core . '\' WHERE `part_no` = \'' . $partNoResult['part_no'] . '\'');
}
I added getValue function to escape posted data to prevent SQL injection.
Try removing this
$res = mysql_result($sel);
And change your while to reference the main query resource
while($row = mysql_fetch_row($sel)) {
I don't understand your logic with your tables though. You're inserting data into the cartons_added table but then you're selecting from cartons_current?
Also, split is deprecated as of PHP 5.3.0
You said five middle "characters", so I'd add quotes around your variable like so:
$query3 = "insert into cartons_current(core) values('$core')";
(Also, there's only about a gazillion answers on SO about SQL injection, and using pdo)
INSERT INTO cartons_current(core)
SELECT
substr(part_no,position('-' IN part_no)+1,position('-' IN substr(part_no,position('-' IN part_no)+1))-1)
FROM cartons_added;

Categories