So I have a database with a table of movies with their respective directors.
I have a form where one can add a director to a movie, but I want to not add duplicates (i.e. someone adds a director to a movie that is already in the movie director table.
I have the following, but for the life of me, I cannot figure out why this still adds the duplicate:
if (isset($_POST["submit"])) {
$movie_id = $_POST[movie];
$director_id = $_POST[director];
echo $movie_id;
echo '<br/>';
echo $director_id;
echo '<br/>';
$add_sql = "INSERT IGNORE INTO MovieDirector (mid, did)
VALUES ($movie_id, $director_id)";
if (mysql_query($add_sql, $db_connection)){
echo "added director to movie ";
}
else {
echo "Failed ";
}
I think you are confused about what the IGNORE modifier keyword does for INSERT statements in MySQL. The role of IGNORE is not to prevent duplicate records from happening, but to make errors silent.
So, there are multiple ways you could go about this:
you could modify your schema to not allow duplicate records and either continue to use the IGNORE keyword, or better yet, handle theerrors
ALTER TABLE MovieDirector ADD UNIQUE INDEX(mid, did);
you could also modify your query to not insert a record if one already exists
IF NOT EXISTS(SELECT * FROM MovieDirector WHERE mid = $movieId AND did = $directorId)
INSERT INTO MovieDirector (mid, did) VALUES ($movieId, $directorId)
You probably want both of the above (probably minus the IGNORE keyword.. that's just going to come and bite you later)
This answer would be incomplete if I did not stress that you should really be using parametrized queries instead of adding the variables directly into the query string!
Related
I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be pushed into it.
It's a MYSQL database and I have to do it in PHP this is what I got so far.
$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
if (!in_array($word, [" ", ""]))
query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")
You have 2 options:
REPLACE
REPLACE INTO table
SET column = 'example'
This will overwrite if the record exists and if not it will create it.
INSERT IGNORE
INSERT IGNORE INTO table
SET column = 'example'
This will ignore the query if already exists and if not it will create it.
Your php query should look like this:
"INSERT IGNORE INTO ID142118_ascii.Woord (woord) VALUES (".$word.")"
put a unique constraint on the column "woord" in the table.
Then you can let your php script insert as many duplicate words as you want to, it will simply fail.
you could either add a part "ignore duplicate" in your query or just ignore the error you will get.
I thinks that will be easiest to do.
edit:
btw I can think of a lot of words containing serveral of the character you are stripping: "foto's", "zee-eend" etc
--
how to make a unique index:
ALTER TABLE asciiwoorden
ADD UNIQUE INDEX somename (Woord);
I'm using PHP in order to create a website where managers have access and review forms that employees have submitted. In the reviewing PHP file, I have created two buttons which basically approve or disapprove the form. After they click on one of the buttons, they are being redirected to another PHP file which actually inserts into the MySQL Database a change in a column I named 'processed'. It changes 0 which is unprocessed to 1, which is processed. The table I am referring to has columns such as formid, fullname, department and other job related stuff, as well as the 'processed' column which allows the managers to see if there is a pending form to be reviewed.
My problem is that I have no idea how to actually allow MySQL to find the proper row and change only the cell with the name 'processed' from 0 to 1 without having to insert every cell again. Here's what I have tried till now:
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "INSERT INTO carforms (processed) where aboveid='$id' and processed='0' and teamformid=$teamformid
VALUES ('0')";
}
else if (isset($_POST['disapproved'])) {
//todo
}
How do I tell SQL to only find the specific row I want and change only one column which is processed?
Also, do I always have to type every column name when I use the INSERT INTO command?
Thanks in advance.
Use the Below code it'll work for you.
$id = $_SESSION[id];
$fullname = $_SESSION[fullname];
$teamformid = $_SESSION[teamformid];
if (isset($_POST['approved'])) {
$sql = "UPDATE `carforms` SET processed = '1' WHERE `aboveid` = '".$id."' AND `teamformid` = '".$teamformid."'";
}
Try:
"UPDATE carforms SET processed = 1 WHERE aboveid = $id AND teamformid = $teamformid"
From what I have interpreted from your question, it seems like you need to use the MySQL UPDATE command. This will update any existing rows.
For example, let's say you have a table called 'forms', consisting of a Primary Key 'form_id' and a field named 'processed'.
If we want to change the value of 'processed' to '1', we would run...
UPDATE forms SET processed = 1 WHERE form_id = [whatever number the form is];
Obviously this only works where the form (with a form_id) exists already
There is no "INSERT...WHERE" in SQL.
To change an existing record there are 2 options, REPLACE or UPDATE. The former will create the record if it does not already exist and has similar syntax to INSERT. UPDATE uses the WHERE clause to identify the record(s) to be changed.
Using REPLACE is tricky. It needs to work out whether it should INSERT a new record or UPDATE an existing one - it does this by checking if the data values presented already exist in a unique index on the table - if you don't have any unique indexes then it will never update a record. Even if you have unique indexes just now, the structure of these may change over time as your application evolves, hence I would recommend NOT using REPLACE for OLTP.
In your question you write:
where aboveid='$id' and processed='0' and teamformid=$teamformid
(it would have been helpful if you had published the relevant part of the schema)
'id' usually describes a unique identifier. So there shouldn't be multiple records with the same id, and therefore the remainder of the WHERE clause is redundant (but does provide an avenue for SQL injection - not a good thing).
If the relevant record in carforms is uniquely identifed by a value for 'id' then your code should be something like:
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
But there's another problem here. There are 3 possible states for a record:
not yet processed
declined
approved
But you've only told us about 2 possible states. Assuming the initial state is null, then the code should be:
$action=0;
if (isset($_POST['approved'])) {
$action=1;
}
$id=(integer)$id;
$sql = "UPDATE carforms SET processed = $action WHERE aboveid=$id";
if ($id &&
(isset($_POST['disapproved']) || isset($_POST['approved']))
) {
// apply the SQL to the database
} else {
// handle the unexpected outcome.
}
I currently have the following update statement but is there anyway that I can make it retain the current values but insert and new values that are not in the db?
If not what would be the best way to achieve this?
UPDATE INTO {refocus_candidate_category} SET canid=?, categoryid=? WHERE canid=? AND categoryid=?",array($emailCheck['id'], $id, $emailCheck['id'], $id));
Function:
$catParams = array_merge(array($emailCheck['id']), $fields['Occupation']);
$catPlaceholders = '?'.str_repeat(',?',count($fields['Occupation'])-1);
$catCheck = CMS::selectQuery("SELECT * FROM {table} WHERE canid=? AND categoryid IN (".$catPlaceholders.")", $catParams);
if($catCheck != FALSE)
{
for($i=0; $i<count($fields['Occupation']); $i++) {
$id = $fields['Occupation'][$i];
CMS::updateQuery("UPDATE INTO {table} SET canid=?, categoryid=? WHERE canid=? AND categoryid=?",array($emailCheck['id'], $id, $emailCheck['id'], $id));
}
echo 'found update';
}
ID Print
$fields['Occupation'][$i] = 1678
It's not clear to me from your question precisely what you mean, but there are a number of alternatives for inserts/updates that deal with missing or already present values.
Firstly, if you just want to insert into mysql and have it either create a new row or replace an existing row (where existing is determined by the primary key matching) use REPLACE INTO instead of INSERT INTO. REPLACE INTO tries an insert, but if the primary key already exists, it turns the query into a DELETE and then retries the INSERT.
If you want to insert a new row but leave an existing row alone if you've already got one, you can either use INSERT IGNORE INTO (which may also fail to insert if you've got your data types or column info wrong...) or INSERT INTO ... ON DUPLICATE KEY UPDATE which allows you to do much finer grained control of how you handle inserts of items that already exist.
There's other options as well, but those are probably the most relevant.
I have a table with 5 columns. ID, name, surname, company & title.
So what I want to do now is to check for duplicate entries during the submitting process, comparing name and surname combination matches. This should then lead to alerting of the duplicate entry and an option to proceed and save it into the database anyway, or cancel the submitting of the content.
Thanks in advance.
You have this option:
setup a conventional index on "(name, surname)"
before each insert, check if the "(name, surname)" combination already exists
if NOT EXISTS, do the insert normaly [here it is up to you to consider the risk that in this 1ms time sb else might have done the same insert]
if EXISTS AND force mode, add the row anyway
if EXISTS AND NOT force mode, proceed to the client according to your specifications
if the client wants to save anyway, repeat operation in force mode.
Here the alternative if you really think this is worth it, is to insert the row anyway and AFTERWARDS check if there were previous rows. If the client wants to keep the record, leave it, otherwise delete it.
rgds
Well here is what I tried, however didn't figure out the optional selection code mentioned in the question yet.
$query = "INSERT INTO phptablo (Name, Surname, Company, Title) VALUES ('$name', '$surname', '$company', '$title')";
$sql = "SELECT Name AND Surname FROM phptablo WHERE Name = '$name' AND Surname= '$surname'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo "$sql" . '<br/><br/>';
echo "$result" . '<br/><br/>';
if ($count==0)
{
if (!mysql_query($query))
{
die('Error: ' . mysql_error());
}
echo "Successful Entry!";
}
else
{
echo "Duplicate Entry found!";
}
I'm QUITE NEW to php & MySQL so can't really make that much use of your much appreciated answers. Any chances to add some code that would give me the option to save it or not?
Where I am at right now, the input isn't saved into the database if a duplicate entry is detected, else it is stored right away. If the code I wrote can't really be altered in a way to save duplicates anyway, I could also use some sort of screen showing the duplicates after saving them, so they can be edited, erased etc.
Okay so the title may be a bit misleading. What I am trying to do is add a favorite system to my site. I have one column for my favorite things and I set it up so after each item ID there is a :. How can I check the string returned from my database (1345:13456:232:524378:324) if it contains 232? If it does I would echo preRend else I would echo insert and insert that ID followed by a :. This is what I have so far:
<?php
session_start();
require_once(".conf.php");
$logged = $_SESSION['logged'];
$user = $_SESSION['user'];
$fwdfav = $_POST['id'];
$query = mysql_query("SELECT * FROM accountController WHERE user='$user'");
if ($logged == 1)
{
while ($row = mysql_fetch_array($query)) {
if ($row['fav-itms'] //This is where I got stuck. How to check if it contains a value.)
{
mysql_query("INSERT INTO accountController ('fav-itms') VALUES ('$fwdfav')");
echo 'inserted';
}
else
{
echo 'preRend';
}
}
}
else
{
echo 'nlog';
}
?>
Thank you so much! I am sure there are a lot of errors here as I am very tired.
The approach you are taking is extremely inefficient and does not take advantage of the fact that you are using a database.
(Btw... I hope this is just example code; you have a giant SQL injection vulnerability in your INSERT query.)
What I would do instead is create a second table that would look something like:
favorites (
id int(11) NOT NULL auto_increment,
user_id int(11),
fav_id int(11)
)
And have each row represent a user-favorite pair. Then you can let MySQL do the heavy lifting of figuring out whether a user has favorited something, e.g.,
SELECT COUNT(*) FROM favorites WHERE user_id = %d AND fav_id = %d;
// Substitute the actual look-up values in using prepared statements
You could also similarly quickly get the actual favorites for a user, etc.
Remember, a database is designed for the explicit purpose of storing and looking up information quickly. PHP is a general-purpose programming language. Where possible, let MySQL do the walking for you.
(This advice is general for a moderately scaled setup. If you need to handle millions of simultaneous users, far more optimization is obviously required, and conventional relational databases might not even be suitable. But I don't get the impression that's where you're at right now.)
You could explode it in array as check, like:
$yourArr = explode(":", $row['fav-itms']);
$checkFor = 232;
if(in_array($checkFor, $yourArr)) {
//it exists
}
else {
//does not exist
}
Did you mean something like this
I know this was posted a while ago but it came up when I did a search.
I have a database storing information for my portfolio, it holds locations for images.
I am working on a page to display the full view of the project. Within the page I need it to check the columns for the images and if any are empty I need it to not display anything.
This is how I've done it.
// connect, select database, query table relevant to page. I have done a query for a specific row.
if($row[columnName1]){
echo '<div> displaying value </div>';
}
if($row[columnName2]){
echo '<div> displaying value </div>';
}
what is happening, if columnName1 in selected row has a value display the value in div else nothing. then on to column 2.
if it is done like this
if(!$row[columnName1]){
//content displayed
}
and the column does not contain a value then what is in between the {} will be ran.
Works the way I needed it to, maybe this will help someone.