setting up warning for duplicate entries in MySQL database - php

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.

Related

how to find out which column MySQL error relates to in PHP?

I can get MySQL errors with mysqli_error() function in php, but I don't want to show user the error that MySQL has been sent. I want to get the name of the field or column that the error relates to it and tell user that your input in 'example' field should be changed. I know that I can use a function like strpos() in PHP to check whether the error expression contains the names of the columns or not, but as you know some of the MySQL error expressions contain names of all the columns in table and here I can't decide next to which input field show error?
is there a function like for example mysqli_error_column() to get the name of the column throws the error? or any other advises?
$sql = "INSERT INTO customers (password, active, email, active_code, submit_date)VALUES('$codedPass', '0', '$email', '$verificationKey', '$currDate')";
$insertResult = mysqli_query($conn,$sql);
if(!$insertResult) {
$queryError = mysqli_error($conn);
if(preg_match("/\b"."email"."\b/",$queryError)) {
$php_input_error['email'] = $error_msg['unknown'];
}
else if(preg_match("/\b"."password"."\b/",$queryError)) {
$php_input_error['pass'] = $error_msg['unknown'];
}
else $php_input_error['general'] = "there's an error with your inputs, please check them again.";
}
I do not think that there is some other way to do that.
However I would advise you completely different solution:
it will be nice to validate data BEFORE sending it to DB (in PHP code).
In such case:
You may implement validation rules of any complexity (length,
allowed symbols, data ordering, validation dependencies between
fields, etc).
You will know everything about an error. So you may show more understandable message to user.
You will decrease load of database server.

mysql don't post dupes to table

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!

Column count doesn't match value count at row 1 when submitting a form

I've been fighting with a bit of code for a week now, not seeing what the heck is wrong...
I have a gaming site I'm trying to build new character sheets for, the form is all done, the action pointing to another page that is strictly the sql for inserting the information into the database. We have good connection, but it is hanging at the second insert statement. The code was working previously, but we had to delete the database and rebuild it, resulting in a rebuild of the insert sql lines.
The first portion of the insert code is:
if($_POST['Submit']=="Submit")
{
$sql="INSERT INTO accounts (log_name,owner,account_type,date_joined) VALUES (\"$_POST[char_name]\",\"$_SESSION[logname]\",\"$_POST[account_type]\",NOW())";
$result = mysql_query($sql)
or die("<p>Couldn't add character.<br/>".mysql_error()." in accounts.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
echo $_SESSION['logname'];
$sql="INSERT INTO topdata (log_name,char_venue,sub_venue,species,char_name,create_date,gender,age,appage,nature,demeanor,concept,description,web_site,view_pword,sfa) VALUES (\"$_SESSION[logname]\",\"$_POST[char_venue]\",\"$_POST[sub_venue]\",\"$_POST[species]\",\"$_POST[char_name]\",NOW(),\"$_POST[gender]\",\"$_POST[age]\",\"$_POST[appage]\",\"$_POST[nature]\",\"$_POST[demeanor]\",\"$_POST[concept]\",\"$_POST[description]\",\"$_POST[web_site]\"\"$_POST[viewpw]\",\"$_POST[sfa]\")";
$result=mysql_query($sql)
or die ("<p>Could not create character.<br/>".mysql_error()." in topdata.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
When the information is entered into the form and submit is hit, I get the following:
1
Could not create character.
Column count doesn't match value count at row 1 in topdata.
Please send this exact message to Savvannis with your character's name.
I look at the database and the information is entered into the accounts table, so that statement is working, but it is hanging up on the topdata table. It's not echoing the $_SESSION['logname'] and looking at the database, it's not saving the owner, which should be $_SESSION['logname'], so I'm wondering if that statement is now somehow incorrect??
I can't figure out what the heck is wrong. Any and all help would be greatly appreciated.
You have missed a comma here: \"$_POST[web_site]\"\"$_POST[viewpw]\" in your second insert SQL.
It should be \"$_POST[web_site]\", \"$_POST[viewpw]\"
First off the error message is telling you that there is an unequal number of columns and values in your SQL
Lets have a look at that
INSERT INTO topdata (
log_name,
char_venue,
sub_venue,
species,
char_name,
create_date,
gender,
age,
appage,
nature,
demeanor,
concept,
description,
web_site,
view_pword,
sfa
) VALUES (
\"$_SESSION[logname]\",
\"$_POST[char_venue]\",
\"$_POST[sub_venue]\",
\"$_POST[species]\",
\"$_POST[char_name]\",
NOW(),
\"$_POST[gender]\",
\"$_POST[age]\",
\"$_POST[appage]\",
\"$_POST[nature]\",
\"$_POST[demeanor]\",
\"$_POST[concept]\",
\"$_POST[description]\",
\"$_POST[web_site]\"\"$_POST[viewpw]\",
\"$_POST[sfa]\"
)";
Now by formatting your SQL (which is vulnerable to sql injection) I've noticed a missing comma between web_site and viewpw values

PHP SQL UPDATE using variables

I currently have a script to upload photos, at the moment it uploads multiple images adding a new row to the mySQL database each time a new one is created. However I want the user to only be able to upload 1 image maximum.
I have therefore changed the register script to insert a row straight in to the database with a default image for each new user that registers.
The image upload script once logged in currently uses the below line to put the data in to the database
$sql2= "INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic'); ";
However this is not how I want this to work; I believe the resolve would be to change this to an UPDATE row.
This is causing an issue when I change the line, I believe I have not quite grasped the concept of updating rows in mySQL.
Please can you advise?
$sql2=
"INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
ON DUPLICATE KEY UPDATE title = VALUES(title), size = VALUES(size), type = VALUES(type), reference = VALUES(reference)";
Would solve this if the profile_id column got the index unique.
Behavior
This will INSERT all the data in a new row if the profile_id isn't already added. If it is, it will run an UPDATE instead.
However your code is pretty much begging for mysql injections. Do read up on this before it ruins your site.
Bobby tables, for your consideration.
Read up on DUPLICATE KEY here.
Assuming that profile_id is your unique key:
$sql2= "
INSERT INTO
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
on duplicate key update set title='$title', size='$size', type='$type', reference='$reference'; ";
You can also use the replace into:
$sql2= "
Replace into
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')";
I think this question misses some information.
You might want to look into the REPLACE INTO statement
Or look up the MySQL UPDATE reference manual page
What you need is to execute the UPDATE sql statement:
$sql3= "UPDATE `profile_photo` SET `title`='" . mysql_real_escale_string($title) .
"', `size`='" . mysql_real_escape_string($size) .
"', `type`='" . mysql_real_escape_string($type) .
"', `reference`='" . mysql_real_escape_string($pic) .
"' WHERE `profile_id`=" . $_SESSION['id'];
Maybe the solution is Replace?

PHP check if MySQL table contains value

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.

Categories