Search mysql database before inserting data - php

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.

Related

Some queries in PDO php executing and some are not

I am trying to enter a whole table in itself changing the city variable but when I create a temp table to store data the insert statement to insert data back in original statement not working. Here is the code
<?php
if(isset($_POST['btnsub'])){
$city=$_POST['city'];
$query= $conn->query("create table from_php like menuinstant;
insert into from_php select * from menuinstant where city='Kota';
update from_php set id = replace(id,'Kota','.$city.');
update from_php set city = replace(city,'Kota','.$city.');
insert into menuinstant select * from from_php;
drop table from_php
");
echo "table created";
}
?>
The insert into menuinstant is not executing even the drop query after that is also working. Help me out.
almost all database/sql wrappers will only allow exactly ONE query per call. so your $conn->query([5queries]) should be five $conn->query([1stquery]); $conn->query([2ndquery]); ...
update1:
You should/could also check for errors:
$result = $conn->query('[Your query here]');
if($result === false) {
die(print_r($conn->errorInfo(),true));
}
update2: please read up on mysql injections. for example http://php.net/manual/en/security.database.sql-injection.php

Insert id from from one table and insert it into another one. Mysql + PHP [duplicate]

This question already has answers here:
How to get the last field in a Mysql database with PHP?
(5 answers)
Closed 9 years ago.
I am working on a register user form and I have two tables in mysql. What I want to do is when a new user has registered, take the id (which primary key) of that user and insert it into another table. What is the best way to do that?
Thanks in advance.
You need to use mysql_insert_id for this purpose. Here is an example:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
First insert the user details into users table and get inserted user id using mysql_insert_id. and use that user id to insert into another table.
AS ON GETTING IT ON PHP
GET LAST INSERT ID HERE
BUT IF YOU INTEND TO GET IT USING MYSQL QUERY
use stored procedure to store last insert id to a variable then generete your second query
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
SET #last_id_in_T1 = LAST_INSERT_ID();
INSERT INTO T2 (col1,col2) VALUES (#last_id_in_T1,val2);
or direct insert after your first insert
INSERT INTO T1 (col1,col2) VALUES (val1,val2);
INSERT INTO T2 (col1,col2) VALUES (LAST_INSERT_ID(),val2);
Use any of transaction query for writing:
Following is in CI pattern:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('AN SQL QUERY...');
if(!$this->db->trans_complete()){
$this->db->trans_rollback();
}
$query1= "INSERT INTO employee ( username, email,...)
VALUES ('".$_POST["username"]."', ...)";
if($result1 = mysql_query($query1))
{
$emp_id = mysql_insert_id(); // last created id by above query
$query2= "INSERT INTO dept ( emp_id, dept_name, ...)
VALUES ('".$emp_id."', '".$_POST["dept_name"]."',...)";
if($result2 = mysql_query($query2))
{
//success msg
}
}
Another neat way to do it at do it at Database level itself is to used Stored Procedure
Look at this solution to see an example of how to do it. You will have to check how Stored procedures work in your specific database to get the specific syntax. This makes it error free even if someone refactors or moves around the code and more efficient.
Using trigger the Mysql on database-level. For example, I have two tables:
user(id int primary key, nombre varchar(50));
replication(id_r int primary key, nombre_r varchar(50));
Using the trigger:
create trigger user_r after insert on user
for each row
insert into replication(id_r, nombre_r)
select u.id, u.nombre
from user u
where u.id=NEW.id and u.nombre=NEW.nombre;

PHPMySQL: How to determine if value already exists in database

I have a form button that I need to do two different things, based on user input and whether that input already exists in my database. If the input DOES NOT exist, then the button will create a new record. If it DOES exist, then the existing record will be updated.
Here's my PDO query as it stands now:
/* First, we need to discover whether the Proposal No. entered already exists in the
database. If it doesn't, then a new record will be created. If
it does, then an existing record will be updated. */
$pNoExists = $con->prepare("SELECT ProposalNo FROM ptfp1");
$pNoExists->execute();
$row = $pNoExists->fetch(PDO::FETCH_ASSOC);
When I run $row = $pNoExists->fetch(PDO::FETCH_ASSOC); through a while loop, all of the values for the field are present. Now I just need some guidance on how to use that in my button setup. This is what I want to do:
if($_POST['ButtonPush'] && input doesn't exist) {
Create new record;
}
else {
Update existing record;
}
Simple, right? But it's eluding me.
Given what you have, I would do:
if($_POST['ButtonPush'] && array_search($all_values, $input_value)) {
Create new
}
else {
Update
}
However, like the comment above, you may want to simply add a where clause to your "SELECT" statement so you are not grabbing the entire database table contents every time. And, one could even convert the SELECT in to a SELECT COUNT to bring down the amount of data being requested.
You could use SELECT count(*) FROM ptfp1 WHERE ProposalNo = :input
Than check if the value you get is bigger than one. If it is, update it:
UPDATE ptfp1 set ... where ProposalNo = :input
else
INSERT INTO ptfp1(...) VALUES (...)
Assuming ProposalNo has a unique index in the table, you can do it all in one query:
INSERT INTO ptfp1 (ProposalNo, colA, colB, colC, ...)
VALUES (:ProposalNo, :colA, :colB, :colC, ...)
ON DUPLICATE KEY
UPDATE colA = VALUES(colA), colB = VALUES(colB), colC = VALUES(colC), ...
Documentation
Figured out an answer. Just use the user's input (stored in a session variable) in my SELECT statement:
$pNoExists = $con->prepare("SELECT ProposalNo FROM ptfp1 WHERE ProposalNo =
'".$_SESSION['ProposalNo']."'");
$pNoExists->execute();
$row = $pNoExists->fetch(PDO::FETCH_ASSOC);
And the button:
if($_POST['ButtonPush'] && !$row['ProposalNo']) {
Write new record;
}
else {
Update existing record;
}
Hiding in plain sight!

mysqli insert - but only if not a duplicate [duplicate]

This question already has answers here:
if not exists insert in MySql
(2 answers)
Closed 9 years ago.
I'm a Java developer who just got handed the task of "some quick easy DB stuff" - except I don't know much about PHP/MySQL...I need to insert a record into a DB - but only if the email field doesn't match one that already exists in the DB. Here's what I've gleaned so far for my PHP code:
// Grab the values from the HTML form:
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
// Now search the DB to see if a record with this email already exists:
$mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
Now I need to see if anything came back from that search - meaning the email already exists - and if so I need to alert the user, otherwise I can go ahead and insert the new info into the DB using:
$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Any ideas?
Working from your code, this should point you in the right direction. there are, perhaps, better ways to structure your database that will make better use of it.
<?php
$mysqli = new mysqli("localhost", "iodine", "iodine","iodine");
// Grab the values from the HTML form:
/*
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
*/
$newUserName = "Test User";
$newUserEmail = "test4#example.com";
// Now search the DB to see if a record with this email already exists:
echo "SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'", "\n";
$result = $mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
if (!$result) {
die($mysqli->error);
}
echo "num_rows = ".$result->num_rows."\n";
if ($result->num_rows > 0) {
echo "Duplicate email\n";
// do something to alert user about non-unique email
} else {
$result = $mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
if ($result === false) {echo "SQL error:".$mysqli->error;}
}
?>
Consider putting a unique index on this particular table. The following code will add the index and remove any current duplicates:
ALTER IGNORE TABLE `RegisteredUsersTable` ADD UNIQUE INDEX unique_email (`UserEmail`);
Once this is added, use INSERT IGNORE or INSERT...ON DUPLICATE KEY UPDATE. They will only preform the insert if there is no duplicates.
$mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Mysql will throw an error because the email is already in the database. However, the IGNORE command is telling the script to not pay any attention to errors for this query because, in this case, you expect it for a duplicate row.
Also, there is a way to alert your user with a failure or success message, even with INSERT IGNORE. Use MYSQL LAST_INSERT_ID(). If an ID was given, it was inserted. If not, then the email was already there (or there was another error).
As for your first query, to soften the load on servers, use count() instead.
$mysqli->query("SELECT count(*) FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
This way, you can just check if you've gotten a result higher than 1. If the result is greater than 1, then the username exists (Since a row was returned).
To check the data returned, you need to simply execute the statement, then fetch the results. Part of the fun is learning, so here's the documentation

If inputs exist, dont insert, else insert PHP mysql

I've just started with php, and i wondered if anyone can help.
i have this
$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!
split it into 2 queries:
1) check if event exists. If yes then do nothing, else insert a new event
2) continue with your query. this way the event will allays exist when inserting your data
This is something that can be done through MySQL alone.
Setup a unique key for the event column by running the following MySQL Command on your table:
CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);
For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Do this for every possible table you expect to see in the $tbl_name variable.
Then, change your PHP Query:
$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html
INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).
Try:
$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)
if ($num_rows > 0) {
// do nothing
}
else {
$sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result = mysql_query($sql);
}
As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.

Categories