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.
Related
Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?
Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";
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;
I am trying to insert into two tables the mother table and the child table : but the mother table gets the data and the child table does not : I get the error
Cannot add or update a child row: a foreign key constraint fails (portfolio.players, CONSTRAINT players_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE)
And bellow is my code :
$query="INSERT INTO users(email,date)
VALUES('$email','$date')";
$user_result = mysql_query($query);
/*last inserted Id */
$id_last = ("SELECT LAST_INSERT_ID()");
$res = mysql_query($id_last);
$last_id = mysql_fetch_array($res);
/*last inserted Id ends*/
/*insert query */
$sql="INSERT INTO
players(name, surname, position, contact_number, email, username, password, date, user_id)
VALUES('$name ','$surname','$position','$contact_number','$email','$username','$password', '$date', '$last_id')";
$result = mysql_query($sql)or die (mysql_error());
/*if something goes wrong then tell the user*/
if($result){
echo "Player Successfully added</br>";
}
else {
echo "We are sorry no player inserted ";
}
$last_id = mysql_fetch_array($res);
mysql_fetch_array returns array, to get actual id you should use $last_id[0]. Also there is function for that: mysql_insert_id. While looking on linked manual page, please pay attention to big red frame, and continue developing with either mysqli or PDO.
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();
?>
I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id........name........email...........date...........score
1........J.Doe.....j.doe#xyz.com.....7/27/11.........4
You're looking for INSERT... ON DUPLICATE KEY syntax
"INSERT INTO scoreboard (`name`, `email`, `date`, `score`) ".
" VALUES ('$name', '$email', '$date', '$score') ".
"ON DUPLICATE KEY UPDATE `score` = $sum";
Aside:
Use mysql_real_escape_string!
$name = mysql_real_escape_string( $_POST['name'] );
$score = mysql_real_escape_string( $_POST['submitscore'] );
$email = mysql_real_escape_string( $_POST['email'] );
$date = date("F j, Y, g:i a");//The date and time
EDIT
First, this doesn't really work unless you have a column SUM(SCORE):
$sum = ($row['SUM(score)']+$score);
If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use $row['score']. If you need to add to an existing score you don't need to select for the value (thanks to a1ex07 for pointing this out)
ON DUPLICATE KEY UPDATE `score` = $score + score
This line is incorrect:
$sum = ($row['SUM(score)']+$score);
You probably want to replace it by:
$sum = ($row['score']+$score);
As you are new to PHP/MySQL I recommend you to read about MySQL Injections as your queries contain potential risks.
I'd have a database table to hold quizzes; a database table for members; and a database table that contains foreign keys to both tables along with a score so only one record can be created for each member and each quiz.
I'd also save the score in a session when the user finishes the quiz so the user can't then just submit any old score to your database; the score entered is the score your application generated.
This way, you can then just query SUM(score) of a member based on that member's ID.