Update the row if value matches else Insert a new row - php

I'm creating a table for student to insert for Entrance Exam for with following value(id (primary key), name, symbol, address)
and later they will print admit card.
If they double enter their value and if there already exist an row for same value of symbol, I would like to update name and address to new value if there instead of inserting new one.
How can I do that..?
My Mysql Database is
$name = $_POST['name'];
$symbol = $_POST['symbol'];
$address = $_POST['address'];
$sql = "
IF NOT EXISTS (SELECT * FROM entrance WHERE symbol = :symbol)
INSERT INTO entrance(
name,
symbol,
address) VALUES(:name,:symbol,:address)
ELSE
UPDATE entrance SET name = :name, address = :address WHERE symbol =
:symbol
";
$q = $db->prepare($sql);
$q->execute(array(':name'=>$a,':symbol'=>$symbol,':address'=>$address,))

You could work with IF NOT EXISTS in your SQL.
IF NOT EXISTS (SELECT * FROM entrance WHERE symbol = :symbol)
INSERT INTO entrance(
name,
symbol,
address) VALUES(:name,:symbol,:address)
ELSE
UPDATE entrance SET name = :name, address = :address WHERE symbol = :symbol

First check if the data is in database by using select query
$select = "SELECT * FROM entrance WHERE symbol='$symbol'";
If select query return rows>0 then run update query else insert Query

Related

INSERT into MYSQL and then before closing the connection select the insert id and then adding this id to 3 other tables

I am pretty new to the world of SQL so sorry for my ignorance on this.
I have a form on an admin page that adds a player to a team database. When the form is submitted what I need to have happen is:
The player gets inserted into players table (player_id is Primary key and used in next step).
A select statement runs to get the player_id.
Then inserts that into 2 other tables:
team_players and cards.
Below is the best representation of what I have tried:
if(isset($_POST['submit'])){
$first_name = mysqli_real_escape_string($con2, $_POST['first_name']);
$last_name = mysqli_real_escape_string($con2, $_POST['last_name']);
$email = mysqli_real_escape_string($con2, $_POST['email']);
$validation_code = md5($email + microtime());
$sql0 ="INSERT INTO players
(first_name, last_name, email, validation_code)
VALUES ('$first_name', '$last_name','$email', '$validation_code')";
$sql01 = "SELECT player_id FROM players WHERE email='$email'";
$result01 = $con2->query($sql01);
if ($result01->num_rows > 0) {
$row01 = $result01->fetch_assoc();
$playerID = $row01['player_id'];
echo $playerID; //In for debugging. Sometimes it works sometimes it doesn't
$sql02 = "INSERT INTO team_players, cards (player_id, team_id)
VALUES('$playerID', '$id')";
Thanks for any help on this.
You cannot insert into two tables using one query.
You can use a transaction and have both of them be contained within one transaction.
Otherwise execute two separate queries for each insertion.
One more thing, you have not executed the query for inserting to first table
START TRANSACTION;
INSERT INTO team_players (player_id, team_id) VALUES (...);
INSERT INTO cards (player_id, team_id) VALUES (...);
COMMIT;

Update MYSQL row with non null value only

i have a table contain huge number of rows and i need to update row with specific ID, for example assume i have a row with below details:
Id= 1
Name= lessa
Address = USA
now i used below PHP code to update the row:
<?php
$con = mysqli_connect("localhost","MyUserName","MyPassword","DB");
$id = '1';
$name = "";
$address = "UK";
// update only non value items
$r=mysqli_query($sql);
mysqli_close($con);
?>
now my issue since the value of address is changed from USA to UK i need to update this value only, also since the name value is nothing the name should be remain so after update the row should be like below:
ID=1
Name = lessa
Address = UK
Also if in another time the name value changed and address remain the same i need to update the name only.
also assume i have 100 column not only three as this example.
any help for write the update statement will be appreciated.
Update:
I use below code but no update happen:
<?php
$con = mysqli_connect(DB info);
$id = 'jo_12';
$name = "";
$address = "UK";
$sql = "UPDATE info
SET name = IF(? = '', name, ?),
address = IF(? = '', address, ?)
WHERE id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("ssssi", $name, $name, $address, $address, $id);
$stmt->execute();
mysqli_close($con);
?>
Put tests in the UPDATE query:
$sql = "UPDATE yourTable
SET name = IF(? = '', name, ?),
address = IF(? = '', address, ?)
WHERE id = ?";
$stmt = $con->prepare($sql) or die ($con->error);
$stmt->bind_param("sssss", $name, $name, $address, $address, $id);
$stmt->execute();
The IF() tests assign the old value of the column back to it if the variable is empty.
Try to use this SQL query:
UPDATE table_name SET Address='UK' WHERE ID=1
You can of course substitute ID=1 for any other number.

Insert after grabbing a mysqli_insert_id value

This has sorta been an on going problem for me, after I insert into a table in my db I grab the ID that was just generated using $user_id_number = mysqli_insert_id($dbc);
I need to take that value and insert it into the table I just inserted into but into a different column, this is my code
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query1 = "INSERT INTO user_register (user_email, user_password, register_date_time) VALUES ('$user_email', SHA('$user_password1'), NOW())";
mysqli_query($dbc, $query1);
//Grab the primary id key that was just created
$user_id_number = mysqli_insert_id($dbc);
//store Id key in variable for new directory name
$directory_name = 'user_id_'.$user_id_number;
//use id key to name directory
mkdir($directory_name);
//Add the new directory name in user_register table
$query2 = "UPDATE `user_register` SET `client_folder`= [$directory_name] WHERE user_id = $user_id_number";
mysqli_query($dbc, $query2);
It does the first insert, created the directory but does not go on to update the directory name into the table?!!? I have also tried insert and get the same result...any ideas?
ps...I am trying to create a new directory that is named with info from the primary id then can be called later so I can put a new directory in that directory
Since $directory name is a string you will need to surround with quotes
client_folder = '$directory_name' WHERE user_id = $user_id_number";
//^here //^and here
$query2 = "UPDATE user_register SET client_folder= [$directory_name*]* WHERE user_id = $user_id_number";
Remove the "[" and "]"
The update query:
$query2 = "UPDATE `user_register` SET `client_folder`= '$directory_name' WHERE user_id = $user_id_number";

Deciding on ON DUPLICATE KEY UPDATE query?

see the code below, it work really.
It insert into affiliate table if a record do not exist.
If it has been inserted in affiliate table then it will add a new record in phone table. However it will need to update phone_id field in affiliate table (new recent record) on the 3rd query - is there a way to reduce this?
$SQLInsert = "INSERT INTO affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$affiliatePhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
$q = mysql_query($SQLInsert);
// If a record has been inserted into affiliate table and then phone table
// then it need to update phone_id field in affiliate table.
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = '$affiliatePhoneID'";
mysql_query($SQLUpdate) or die(mysql_error());
}
Maybe you could change the database sheme so the phone table holds the forainkey to the affilaite table. so you dont need to update the affilate table twice.
If that is not what you want, you could try to UPDATE the phone table first,
and after that the affilate table.

Problem with syntax error

Hi guys am fighting with a syntax error of my sql, saying exactly:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax"
Even though the code is working and doing what I wanted I still get the syntax error info!
and here is the code:
$person_id =mysql_query("SELECT person_id FROM person WHERE firstname='$array[0]' AND lastname='$array[1]' AND city='$array[2]' ")
or die(mysql_error());
if (mysql_num_rows($person_id) )
{
print 'user is already in table';
}
else
{
mysql_query ("INSERT INTO person VALUES (NULL, '$array[0]' ,'$array[1]' , '$array[2]' ")
or die(mysql_error());
$person_id = mysql_insert_id();
}
$address_id =mysql_query("SELECT address_id FROM address WHERE street='$array[3]' AND city='$array[4]' AND region='$array[5]'")
or die(mysql_error());
if (mysql_num_rows($address_id) )
{
print ' already in table';
}
else
{
mysql_query ("INSERT INTO address VALUES (NULL, '$array[3]', '$array[4]', '$array[5]'")
or die(mysql_error());
$address_id = mysql_insert_id();
}
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)")
or die(mysql_error());
Thanks for any suggestions
It's probably because you haven't escaped your values...
Try:
$query = "SELECT age FROM person WHERE name='".mysql_real_escape_string($array[0])."' AND lastname='".mysql_real_escape_string($array[1])."' AND city='".mysql_real_escape_string($array[2])."'";
And read up on SQL injection.
EDIT
I think your problem is that you are trying to pass mysql result resources directly into a string, without fetching the actual values first.
Try this:
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the person already exists in the database, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]')";
mysql_query($query) or die(mysql_error());
$person_id = mysql_insert_id();
}
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// INSERT a record linking person and address
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)") or die(mysql_error());
ANOTHER EDIT
Firstly, I have modified the code above - added a couple of comments, corrected a couple of small errors where the wrong variable was referenced and re-spaced it to make it more readable.
Secondly...
You are getting that additional error because you are trying to insert a new row into your person_address table, which doesn't seem to have a sensibly configured primary key. The easy work around to the problem you currently have is to run a SELECT against this table to see if you have already got a record for that user, then if you have you can do an UPDATE instead of the INSERT to alter the existing record.
However, if I understand what your doing here correctly, you don't actually need the person_address table, you just need to add another integer column to the person table to hold the ID of the corresponding row in the address table. Doing this would make many of your future queries potentially much simpler and more efficient as it will be much easier to SELECT data from both tables at once (you could do it with your current structure but it would be much more confusing and inefficient).
The following code example could be used if you add another integer column on the end of your person, and call that column address_id. You will notice it's very similar to the above, but there are two key differences:
We do the address stuff first, since we will keep track of the relation in the person record
We do an UPDATE only if we find a person, otherwise we just INSERT a new person as before
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// See if the person already exists in the database, UPDATE if he does, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
$query = "UPDATE person SET address_id = '$address_id' WHERE person_id = '$person_id'";
mysql_query($query) or die(mysql_error());
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]', '$address_id')";
mysql_query($query) or die(mysql_error());
}
If we structure the database in this way, it allows us to do this:
SELECT person.*, address.* FROM person, address WHERE person.address_id = address.address_id AND [some other set of conditions]
Which will return the person record, and the address record, in the same result set, all nicely matched up for you by the database.
YET ANOTHER EDIT
You need to add an auto-increment primary key to the person_address table, and perform a SELECT on it to make sure you are not adding duplicate records.
You should replace the final INSERT statement with the following code segment. This code assumes that you have a primary key in the person_address table called relation_id. It also assumes that the id field names in this table are named in the same way as they are in the other two tables.
// See if a relation record already exists for this user
// If it does, UPDATE it if the address is different
// If it doesn't, INSERT an new relation record
$query = "SELECT relation_id, address_id FROM person_address WHERE person_id = '$person_id' LIMIT 1";
$relation = mysql_query($query);
if ( mysql_num_rows($relation) ) {
$relation = mysql_fetch_assoc($relation);
if ($relation['address_id'] == $address_id) {
print 'The record is identical to an existing record and was not changed';
} else {
$relation_id = $relation['relation_id'];
$query = "UPDATE person_address SET address_id = '$address_id' WHERE relation_id = '$relation_id'";
mysql_query($query) or die(mysql_error());
}
} else {
$query = "INSERT INTO person_address VALUES(NULL, '$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
EVEN MORE EDITING
Try this to replace the code from above:
// See if a relation record already exists for this user
// If it doesn't, INSERT an new relation record
$query = "SELECT person_id FROM person_address WHERE person_id = '$person_id' AND address_id = '$address_id' LIMIT 1";
$relation = mysql_query($query);
if ( !mysql_num_rows($relation) ) {
$query = "INSERT INTO person_address VALUES('$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
You cannot use array values like that inside of quotes - instead you could, for example, separate the values from the query using dots.
$query = "SELECT age FROM person WHERE name='".$array[0]."' AND lastname='".$array[1]."' AND city='".$array[2]."'";
the second and fourth query do not have an ending ')' at the end of the values

Categories