prevent insert data to database if specific atribute already exist - php

I want to prevent duplicate values into a database table from a form using PHP.
I have a table data on database that have atribute dataid(auto increment as primary key), data1, data2.
And I have a simple form like this
<h2>Enter your data</h2>
<form action="script.php" method="post">
Data 1:<input type="text" name="data1" /></p>
Data 2:<textarea name="data2"></textarea></p>
<input type="submit" name="submit" value="Add Data" />
</form>
It's script.php for inserting data to database
<?php
if(isset($_POST['submit']))
{
//connect to the database
$conn = mysql_connect('host', 'username', 'password', 'dbname') or die(mysql_error());
//insert results from the form input
$query = "INSERT INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";
$result = mysql_query($conn, $query) or die(mysql_error());
}
?>
but it will insert any data from the form to database.
How can I prevent insert data to database if data1 already exist?

The solution to your problem is to make the column unique so the database takes care of enforcing this constraint. You can do this by creating a unique index or constraint:
alter table data add constraint unq_data_data1 unique (data1);
You can then use this in an insert to ignore duplicates by using on duplicate key update:
INSERT INTO data(data1, data2)
VALUES('$_POST[data1]', '$_POST[data2]')
ON DUPLICATE KEY UPDATE data1 = VALUES(data1);
The ON DUPLICATE KEY part doesn't really do anything. It is a no-op.
Also, you should parameterize your queries, so you are not subject to SQL injection and so the query plans can be cached. But that is another matter.

make column data1 unique
ALTER TABLE `data` ADD UNIQUE (`data1`);
change your query like this to ignore insert when data exist
$query = "INSERT IGNORE INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";

Related

Storing multiple inputs in database in single query

<form method="post" action="formProcessing.php">
<input type="text" name="uses[]">
<input type="text" name="uses[]">
<input type="text" name="uses[]">
</form>
I have two database tables one called info other uses. info table contain column name inf_num, Is there a way where i can get the last row inf_num and insert the above inputs in uses in one query. For instance if i was to do it manually i would check the last row myself so if it's 10 i would do the below:
INSERT INTO uses (id, uses) VALUES (10, 'useZero'), (10, 'useOne'), (10, 'useTwo');
How would i go about doing it dynamically with php using the above form:
you can create trigger on uses table to set last inserted id of info table.
CREATE TRIGGER uses_before_insert_trigger BEFORE INSERT ON `uses` FOR EACH ROW
BEGIN
SET NEW.id = (select id from info order by id desc LIMIT 1);
END
After, create trigger you can execute insert query directly.
INSERT INTO uses (uses) VALUES ('10'),('20'),('26');
INSERT INTO user( id, uses )
SELECT MAX(id), 'userOne' FROM info
UNION ALL
SELECT MAX(id), 'userTwo' FROM info;
Try To Make A Query Like This
<?php
//Your input is array of your input.
$yourInput = array(10,20,26);
$query = "INSERT INTO uses (id, uses) VALUES ";
foreach($yourInput as $value ){
$query .= "(10, '$value')".",";
}
echo $query;
//Output
INSERT INTO uses (id, uses) VALUES (10, '10'),(10, '20'),(10, '26')
Tested Here
Than Execute this Query
But Remember Youe code is not secure. it is possible to do a sql injection so kindly read this note. and make it more secure.
We can make it possible via query as well.
INSERT INTO uses( id, uses ) VALUES ((SELECT MAX(inf_num) from info),
'useOne', (SELECT MAX(inf_num) from info), 'useTwo', (SELECT MAX(inf_num) from
info), 'useThree')

How to insert row id to another table field using php mysql?

I have first table name is conference.
I want to insert table conference row id (81) to another second table name conf_dates
and that have field conf_id use for save conference row id
The issue is that value is empty insert in second table conf_dates as shown in second table image
Here is php code
<?php
$id = $_GET["id"];
$trans = array("strtdate"=>$strtdate,"enddate"=>$enddate,"conf_id"=>$id);
$query = $db->insert($trans,PREFIX."conf_dates");
?>
Here is html code
<p>
<label>Conference ID</label>
<input name="conf_id" class="text-input medium-input" type="text" id="conf_id" value="" />
</p>
Please tell me how to insert row id to another table field?
what are the values of $strtdate, $enddate
Also please share the table structure of "conf_dates" .
$id = intval($_GET["id"]);
check you are getting correct types, and values for variables you trying to insert
You named the input field conf_id while you try to insert $_GET['id'].
You should insert $_GET['conf_id']` instead.

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

Update row if there is a value or insert if not

I have a form where the user inserts data but they can go back to the same page to edit their information. My table structure is:
id (auto int index),
user id (links to other tables),
Doc_Name,
Abstract
I have an insert query:
$user_id = intval($_SESSION['user_id']);
$Doc_Name = mysql_real_escape_string($_POST['Doc_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`) VALUES
('%d','%s','%s')", $user_id, $Doc_Name, $abstract);
However, if their is already a row for this user_id then I want the update query instead:
mysql_query("UPDATE document SET `Doc_Name` = '$Doc_Name', 'abstract='$abstract'
WHERE id='$_SESSION[user_id]'") or die(mysql_error());
Also, so the user knows what they entered, I tried to use this echo in the text box but that didn't work either,
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name"
value="<? echo $row_settings['Doc_Name']; ?>" size="300"> </textarea>
You can use INSERT ... ON DUPLICATE KEY UPDATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE
c=c+1;
You want the INSERT ... ON DUPLICATE UPDATE syntax
for the textarea you can use
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name" size="300"><? echo $row_settings['Doc_Name']; ?></textarea>
everything between the tags is displayed and editable
EDIT: to the other posters: nice, did not know INSERT ON DUPLICATE
the query:
SELECT * FROM document WHERE id='{$SESSION['user_id']}'
php:
if(mysql_num_rows(mysql_query($query)) > 0) {
//code to be executed if id exists
}

Insert new row in a table and auto id number

I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?
Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.
The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()
The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.
Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)
You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php

Categories