Check for duplication before insertion - php

Problem
I have a table tbl_student_courses which join 2 tables student and courses now when data is inserted it is the combination of 2 ids course_id and student_id. I just want there would be no duplication of this combination in tbl_student_courses.
Code
foreach($_POST['sel_course'] as $val) {
$query_std_course = "
INSERT INTO
`tbl_student_courses`
SET
`course_id` = '".$val."',
`std_id` = '".$_POST['std']."',
WHERE NOT EXISTS (
SELECT * FROM `tbl_student_courses` WHERE course_id=$val AND std_id=$std
)";
}
Help
This query giving SQL syntax error.
Can any body help me?
Thanks in advance.

Probably you are missing quotes one inner query values.
You SQL query should look like this
$sql = "
INSERT INTO
`tbl_student_courses`
SET
`course_id` = '".$val."',
`std_id` = '".$_POST['std']."',
WHERE NOT EXISTS (
SELECT * FROM `tbl_student_courses` WHERE course_id='".$val."' AND std_id='".$std."'
)";
NOTE: Inserting in database not prepared statements like std_id = '".$_POST['std']."' is not of a good manner. Consider using PDO or filter data yourself, bec. this can be easily used for SQL Iinjection therefore it is potential security breach.
UPDATE: Try to use ON DUPLICATE KEY UPDATE or INSERT IGNORE INTO table.
You can find more information regarding your implementation - http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html
And read about proposed implementation - http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

The SQL syntax you seek is the MERGE statement, or its equivalent on your platform
http://en.wikipedia.org/wiki/Merge_(SQL)

Related

How to get max of an ID as a PHP variable and insert it into another table where the ID is also max

I have two tables, Requests & Accounting_Fundscenter_Request
I'm creating a SQL query in PHP that updates
Request_ID from Accounting_Fundscenter_Request WHERE ID is max
to
the max Request_ID from Requests
So far I have gotten the max(Request_ID) rom Requests, but I don't know how to take that value in php & sql and update the other Request_ID to equal that value.
Also, I cannot use the syntax "max(id)" because the "max" function will not work in my first query and I don't know why.
Here's what I have so far:
/* GET MAX ID FROM REQUESTS */
$selectMaxID = 'SELECT Request_ID FROM Requests ORDER BY Request_ID DESC LIMIT 1';
$maxIdResult = mysqli_query($conn, $selectMaxID); //run query
if (mysqli_num_rows($maxIdResult) > 0) {
while($maxid = mysqli_fetch_assoc($maxIdResult)) {
echo "Max Request ID: " . $maxid["Request_ID"]. "<br>";
} //echo result of
}
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxId);
This does not work. Is there a way to fix this or maybe do it in one query?
EDIT: with your help I found the solution:
You have many options here:
You can fix the syntax error you have in you insert query execution like this:
$insertFundsCenterMaxIdQuery = sprintf('INSERT INTO Accounting_Fundscenter_Request (Request_ID) VALUES (%d)', $maxid["Request_ID"]);
/* RUN THE QUERY */
$insertFundsCenterMaxId = mysqli_query($conn, $insertFundsCenterMaxIdQuery);
This way you use string formatting to replace the variable instead of directly using $maxid["Request_ID"] in a string.
Please replace %d with %s in case the Request_ID is supposed to be string/varchar.
Or you can follow another approach and just use one query to do the work like this:
INSERT INTO Accounting_Fundscenter_Request (Request_ID)
SELECT MAX(Request_ID) FROM Requests
And just execute this query
You're facing a syntax error in the update query:
$insertFundsCenterMaxId = "INSERT INTO `Accounting_Fundscenter_Request` (
`Request_ID`,
VALUES (
$maxid["Request_ID"],
)
WHERE MAX(`ID`);";
Using the double quotes in that variable hiding in the VALUES part, you are ending the string contained in insertFundsCenterMaxId. Following it is a raw string containing Request_ID which cannot be parsed by PHP. That's simply invalid code.
To solve it, you could start using prepared statements. They will also help you to secure your application against SQL injection.
There is also a solution to the syntax error problem alone - but that will leave your application vulnerable. That's why I haven't included a fix for that, but by checking how to build strings you might find it on your own. But please, please do not use it for this problem. Please.

update a column with a value coming from an inner join

i need to update a lot of db values, so i guess it's better to use a sql statement, maybe creating and uploading a php file and running it from time to time.
in my db i have 3 related tables, let's say
tableA_label
tableB_image
tableC_text
the relations are as follows:
tableaA_label.ImageID refers to tableB_image.ID
tableB_image.TextID refers to tableC_text.ID
my goal is:
update tableA_label.Name
tableA_label.Name = tableC_text.title
where
tableC_text.ID = tableB_image.TextID
and
tableB_image.ID = tableA_label.ImageID
.....
how can accomplish this using an sql statement?
thank you for supporting
Try this query:
UPDATE tableA_label SET
tableA_label.Name = (SELECT TableC_text.title FROM TableC_text INNER
JOIN TableB_image ON TableB_image.TextID = TableC_text.ID
WHERE TableB_image.ID = tableA_label.imageID)

UPDATE sql query and get the updated field in one single query

I'm trying to update a value of a column using the codeigniter query function like this:
$this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');
Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.
If there is another query in between the update and the select, the result would not be correct.
Thanks!
Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:
$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()
The for-update with the transaction prevents another query interfering.
Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to #Nanne for that)

PHP - SQL Query failure, seems valid?

I'm using XMLHttpRequests to call a PHP script on my server, but the query is continuously failing. I've rewritten it several times, am I going about this the wrong way? I've researched statements and seen them written in a very similar fashion.
$query = mysql_query("UPDATE arts SET a_id=((SELECT a_id FROM logs
WHERE unique='{$_GET['unique']}') + ',' + (SELECT id
FROM mf_arts WHERE art='{$_GET['url']}'))
WHERE unique='{$_GET['id']}'");
if(!$query)
{
$fquery = mysql_query("INSERT INTO mf_arts (art,name)
VALUES('{$_GET['url']}','{$_GET['name']}');
UPDATE mf_logs SET a_id=((SELECT a_id FROM mf_logs
WHERE unique='{$_GET['id']}') + ',' + (SELECT id FROM
mf_arts WHERE art='{$_GET['url']}'))
WHERE unique='{$_GET['id']}'");
if(!$fquery) echo("ADD IMPOSSIBRU");
} else echo "1";
I feel like I'm missing a very small, but very important portion. I tried using IF EXISTS originally but I keep encountering the same problem, so I tried to simplify it to a statement after statement sort of hierarchy. Honestly, thanks for any help. StackOverflow is great.
unique is a reserved word see: dev.mysql.com/doc/refman/5.5/en/reserved-words.html
either avoid it, best option or wrap it in back ticks
Multiple queries aren't allowed in mysql_query. After sanitizing your user input, try separating them
if(!$query)
{
mysql_query("INSERT INTO mf_arts (art,name)
VALUES('{$_GET['url']}','{$_GET['name']}')")
or die("ADD IMPOSSIBRU");
mysql_query("UPDATE mf_logs SET a_id=((SELECT a_id FROM mf_logs
WHERE `unique`='{$_GET['id']}') + ',' + (SELECT id FROM
mf_arts WHERE art='{$_GET['url']}'))
WHERE `unique`='{$_GET['id']}'")
or die("ADD IMPOSSIBRU - Update");
echo "1";
}
unique is a reserved keyword, as was explained above, use (``), like:
WHERE `unique`='{$_GET['unique']}'
Use INSERT INTO ... ON DUPLICATE KEY UPDATE ...
dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate
First, as has been mentioned previously, please please please sanitize your queries.
Second, within double quotes, don't use single quotes for array indices.
WHERE unique='{$_GET['unique']}'
should be
WHERE unique='{$_GET[unique]}'

Ensuring Unique Rows Using PHP/MySQL

I have the following code that should, when run, update a table of "victims" of Her Royal Majesty Penelope the Queen of Sheep (it's work for someone, honest), however every time the code is executed it adds all new rows all over again. I was pretty sure I had safeguarded against that, but I guess not. What am I doing wrong here?
require_once 'victims.php';
foreach( $victims as $vic )
{
$vic = mysql_real_escape_string($vic);
if(!(mysql_query("
SELECT * FROM victims
WHERE ".$vic
)))
{
mysql_query("
INSERT INTO victims
(victim, amount)
VALUES( '".$vic."', 0)
");
}
}
You need to change the where clause of your first query to the following:
WHERE victim = $vic
Also, please consider using bind variables as this will protect your code from SQL injection attacks.
You could use an "INSERT ... ON DUPLICATE KEY" query instead, which will guarantee that existing rows won't be duplicated, but only updated. Assuming vic is the table's primary key, you'd do:
INSERT INTO victims (victim, amount)
VALUES ($vic, $amount)
ON DUPLICATE KEY UPDATE amount=VALUES(amount)

Categories