I have registration form which works fine. Now I want to add second query after user is registered. This query should have loop and add exactly 10 new rows in another table. This is the query with loop
if ($conn->query($sql) === TRUE) {
$result = "Request successfully submitted.";
$new_id = $db_con->lastInsertId();
$qty=11;
$sql = "INSERT INTO new_customer (user_id,value1,value2) VALUES";
for($i=0;$i< $qty;$i++){
$sql .= "($new_id,'1','0')";
if($i < ($qty -1 )){
$sql .=",";
}
}
}
I'm not sure if this is correct way of doing this. After user is successfully registered I'm trying to get lastInsertId and loop and insert 10 new rows in new_customer table.
What is happening is that user is successfully registered but nothing is saved in new_customer. What is the problem here?
You need to execute your inner query like below:-
$conn->query($sql);
Add it after inner for loop code.
Also if you are using mysqli_* then you need to use mysqli_insert_id:-
$new_id = $db_con->mysqli_insert_id;
Related
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
I have a function which gets a particular set of users from a table where a particular WHERE condition is meet.
I need to send each of them a message.
So, I used another function to send the message. And called that function inside he following while loop
while($user= mysqli_fetch_assoc($users_set)){
send_message($user['email']);
}
So, the problem is, the function is called only just one time. (Only with the last value of the loop)
How to fix this problem and make the function called with each value of the loop...
This is the full code...
$query = "SELECT * ";
$query .= "FROM user ";
$query .= "WHERE confirmed = 0";
$user_set = mysqli_query($db_conx, $query);
confirm_query($user_set);
while($user = mysqli_fetch_assoc($user_set)){
send_message($user['email']);
}
Here is the send message function....
function send_message($email){
global $db_conx;
$invitee_user = get_user_by_email($email);
$query5 = "INSERT INTO notification(";
$query5 .= "description, user_id";
$query5 .= ") VALUES(";
$query5 .= "'You have been confirmed'";
$query5 .= ", {$invitee_user['id']}";
$query5 .= ")";
$result5 = mysqli_query($db_conx, $query5);
if($result5){
//$_SESSION["message"] = "Notification sent". \mysqli_error($db_conx);
return "OK";
}else{
//$_SESSION["message"] = "Failed to send notification". mysqli_error($db_conx);
}
}
Here is the code for confirm_query()
function confirm_query($result_set){
if(!$result_set){
die("Fatal Error Occured : Database Query Failed Report this error");
}
}
I would just boil this down to one query and get rid of all the looping stuff
INSERT INTO notification (description, user_id)
SELECT 'You have been confirmed', user_id
FROM user
WHERE confirmed = 0
Your current logic is really convoluted.
You query the user table to get the user email field, then pass that email as parameter to your function only to then turn around and (I presume) look up the user ID based on email (when you already had this information from your initial query), then you make insert.
This means that for every record you return from first query, you need to do 2 queries to insert to the notification table. So if you had 100 results you would end up doing a total of at least 201 queries to complete the insertions.
Using my approach you make 1 query regardless of how many rows are affected.
One takeaway that you should get from this is that, anytime you see yourself trying to do some sort of nested querying, you should recognize this as an anti-pattern (a coding pattern that you do not want to typically use). There is usually a better approach that can be taken if you rethink how you are writing your queries.
I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup
I'm kind of a stuck in searching for a solution.
I need to check if an input data $coupon from the form (after "post" action) equals data in the existing MySQL table called Serial, in the row $Coupon. If those two entries match i need the one in table "Serial" removed (DELETED From). In the other case I need to display an Error, maybe like echo "The coupon number you've entered is invalid".
Now i have the following code, but it doesnt do the check.
$query4="SELECT EXISTS(SELECT 1 FROM serial WHERE Coupon='$coupon')";
$result = mysql_query($query4);
if($result){
echo "Bravo!";
}
else{
"The coupon number you've entered is invalid";
exit;
}
// Delete data from mysql
$query2="DELETE FROM serial WHERE Coupon = '$coupon'";
$result = mysql_query($query2);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Some info";
}
else {
die(mysql_error());
}
Appreciate any ideas greatly!
You've created a race condition for yourself. The fact that the coupon exists when you run the SELECT statement does not mean that it will exist when you run the delete statement, especially if this is a web app, or multi-threaded/multi-process.
The DELETE statement deletes rows from tbl_name and returns a count of the number of deleted rows. This count can be obtained by calling the ROW_COUNT() function.
Run your DELETE unconditionally, then use the ROW_COUNT to see if it was there and got deleted or wasn't ever there.
First of all phase out mysql_* functionality or you have bigger problems than checking the result. Your code is vulnerable to SQL Injection. Use PDO or MySQLi instead.
Secondly, why do you need EXISTS in the first query at all?
Here is the solution in PDO:
$query = 'SELECT 1 FROM serial WHERE Coupon = :coupon';
$stmt = PDO->prepare($query);
$stmt->bindParam(':coupon', $coupon, DB::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0) {
//query 2
$query2 = "DELETE FROM serial WHERE Coupon = :coupon";
$stmt2 = PDO->prepare($query2);
$stmt2->bindParam(':coupon', $coupon, DB::PARAM_STR);
if ($stmt2->execute()) {
echo 'Success';
} else {
echo 'Unable to Delete';
}
} else {
echo 'Selected Coupon Is Invalid';
}
OR MORE SIMPLY IN ONE QUERY:
$query = 'DELETE FROM serial WHERE coupon = :coupon';
$stmt = PDO->prepare($query);
$stmt->bindParam(':coupon', $coupon, DB::PARAM_STR);
if ($stmt->execute()) {
echo 'Success';
} else {
echo 'failure, invalid coupon';
}
You can actually just do SELECT 1 FROM serial...
Then:
$result = mysql_query($query4);
if (mysql_num_rows($result)) {
If it returns a row, you know it exists. You can also add LIMIT 1 to the query to make it faster.
By the way, your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli.
Following up from mluebke's answer:
// Delete data from mysql
$query="DELETE FROM serial WHERE Coupon = '$coupon'";
mysql_query($query);
//Did we delete something?
if (mysql_affected_rows()) {
echo "Bravo!";
}
else{
"The coupon number you've entered is invalid";
exit;
}
http://www.php.net/manual/en/function.mysql-affected-rows.php
http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_row-count
In my site, I have a page to create an site page (addpage.php) and then send the user to a listing of all pages (pages.php), from which they can click on the page they'd like to edit (editpage.php).
I do this because my editpage.php uses the page_id variable to select the page's info from the database and I don't know how to select that variable without first going to pages.php to list all those variables.
I'd like to be able to complete addpage.php and then GO DIRECTLY to editpage.php - but how do I select the page_id that will only just be created on the insert into the database?
My code on addpage.php is basically
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
$id=mysql_insert_id();
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
You can check php manual.
You have to do a query to your database, asking what've been the last inserted id. You can do this running this query:
SELECT LAST_INSERT_ID() as lastId
Then you get the value as you do with any regular query (because this is a regular query actually).
In php there's a function called mysql-insert-id which is more elgant.
Good luck!
If you're using mysql, you can get the ID of the last insert by running the following query SELECT LAST_INSERT_ID(). This will get you the ID.