MySQL - Updating values in row while keeping primary key - php

Scenario:
I have got a client, php script and a MySQL database. I am sending information from the client to the database which the values include the name and favorite color. I have got 2 rows in MySQL database.
Name | Favorite Color
Johnny | Green
Where Name is a primary key.
Every time, the client would be sending both his name and favorite color. So if name (primary key) exist, it shows error. How should I set my php script to react if the client wants to update his favorite color? In other words, keep primary key but update favorite color.
script.php
<?php
mysql_connect("localhost","root","")
mysql_select_db("Information");
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$sql=mysql_query("insert into Male (name, color) VALUES ('$name','$color')");
mysql_close();

$sql=mysql_query("INSERT INTO Male (name, color) VALUES ('".$name."', '".$color."')
ON DUPLICATE KEY UPDATE color='".$color."'");
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

You are looking for the UPDATE SQL statement. This will update an existing row:
$sql = mysql_query("UPDATE Male SET color = '$color' WHERE name = '$name'");
Alternatively you can use INSERT ... ON DUPLICATE KEY UPDATE.
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
$sql = mysql_query("INSERT INTO Male (name, color) VALUES ('$name','$color')
ON DUPLICATE KEY UPDATE color = '$color'");
MySQL offers an SQL extension, namely REPLACE, which will insert a new row, if none exists.
$sql = mysql_query("REPLACE INTO Male (name, color) VALUES ('$name','$color')");

You'll want to modify your mysql_query with an update statement instead of insert. Something like this.
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$sql=mysql_query("UPDATE Male SET color = '".$color."' WHERE name = '".$name."'");
mysql.close();

<?php
mysql_connect("localhost","root","")
mysql_select_db("Information");
$name = mysql_real_escape_string($_POST["name"]);
$color = mysql_real_escape_string($_POST["color"]);
$query = mysql_query("select name from Male where name = '$name'");
if(mysql_num_rows($query) > 0) {
mysql_query("update Male set color='$color' where name='$name'");
} else {
mysql_query("insert into Male (name, color) VALUES ('$name','$color')");
}
mysql.close();
?>

Related

insert images in another table with foreign key

I have two tables in my db, telephones(id, title, price) and images(id, tp_id, photos) I went in the images table and put a foreign key on the tp_id column to match the id in the telephones table so that every image is linked to a telephone. But the problem is my images go into the table fine but the tp_id column always has the value of 0, what I am missing here? can somebody guide me? Thanks
PS: I know about the security vulnerability of my code I am just doing some test here!
<?php
if (isset($_POST['submit'])) {
include 'dbconnect.php';
for ($i = 0; $i < count($_FILES["photo"]["name"]); $i++) {
$target = "img/"; //This is the directory where images will be saved
$target_files = $target . basename($_FILES['photo']['name'][$i]); //This gets all the other information from the form
$ad_title = $_POST['title'];
$ad_price = $_POST['price'];
$ad_photo = $target . ($_FILES['photo']['name'][$i]);
if (!move_uploaded_file($_FILES['photo']['tmp_name'][$i], $target_files)) { //Tells you if its all ok
echo "Sorry, there was a problem uploading your file.";
} else { //Gives and error if its not
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$sql1 = "INSERT INTO images (photos) VALUES ('$ad_photo') ";
$conn->query($sql1);
//Writes the photo to the server
header('location: addconfirm.php');
}
}
}
?>
get the last inserted primary key value using this
$last_id = $conn->insert_id;
You need to get last insert id form telephones table using $conn->insert_id; and the insert into images table as
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_id=$conn->insert_id;// get last insert id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_id) ";
$conn->query($sql1);
Note:- Your script is Open for sql injection check How can I prevent SQL injection in PHP? to prevent it
Question has already been answered many times Use : MySQL: LAST_INSERT_ID()
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_last_insert_id = $conn->LAST_INSERT_ID;// get last insert id
you should call this function right after you insert to get the latest added id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_last_insert_id) ";
$conn->query($sql1);

Why wont this MySQL Query save

So I have this short script. Its not giving out any error but it will not save into the DB. After I run the script I check the DB and nothing is there.
The db only has two items. (id and fid) ID is set at INT 11 auto and fid is set at VARCHAR 64. Also, I am connecting to my DB just fine.
<?php
$con = mysqli_connect('####', '####', '####', '#####');
if (mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if (isset($_POST['submit'])) {
$fid = $_POST['fid'];
$query = mysqli_query($con, "SELECT * FROM fid where fid = '$fid'");
$row = mysqli_num_rows($query);
if ($row == 1) {
echo 'This Federal Tax ID is already in use.';
} else {
mysqli_query($con, "INSERT INTO `fid` (id, fid) VALUES ('', '$fid')");
}
}
?>
Based on your comment:
It's supposed to be an empty value so the ID auto increments everytime.
That's not how auto-increment works. Your code is explicitly telling the record to not have a value:
"INSERT INTO `fid` (id, fid) VALUES ('', '$fid')"
If the id column is required, this will expectedly fail. (It may also be failing based on the type. You're trying to insert a string, but an auto-increment column would be numeric...)
An auto-increment column doesn't need to be supplied an empty value. Just omit it entirely:
"INSERT INTO `fid` (fid) VALUES ('$fid')"
Additionally, this code is wide open to SQL injection. You're going to want to read up on that. In short, you should use prepared statements which bind to user-input values. Don't concatenate those user-input values directly into your code, that allows the user to inject their own code.
If you want to use AUTO you need to either NOT specify the value at all or else specify a 0 (or NULL if defined as NOT NULL):
Either
INSERT INTO fid (fid) VALUES ('$fid')
or
INSERT INTO fid (id, fid) VALUES (0, '$fid')
or (if id is defined as NOT NULL)
INSERT INTO fid (id, fid) VALUES (NULL, '$fid')
SOURCE: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

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";

doing an update or an insert with sql

I have a website for fantasy golf. I use php to read an xml file and update the sql database using the following
foreach($field->field->children() as $player){
$lastname = ($player['last_name']);
$firstname = ($player['first_name']);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$sSQL = "UPDATE `Sheet1` Set InField= 1 WHERE LastName = '$lastname' AND Firstname = '$firstname'";
$result = mysql_query($sSQL, $conn) or die(mysql_error());
This updates the database INFIELD column with the players on the xml file. My question is how would I go about adding that player to the database if he isn't in it already? So almost like doing and if not in the database--insert new record?
any help would be appreciated.
Make sure you have a unique key on (LastName, FirstName), then use:
INSERT INTO Sheet1 (LastName, FirstName, InField)
VALUES ('$lastname', '$firstname', 1)
ON DUPLICATE KEY UPDATE InField = 1
Documentation
I suggest you condition it.
player =mysql_query(select player_in_table from players_table where player_in_table = playerx)
if(mysql_num_row(player) = 1){
//update
} else {
//update
}

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.

Categories