create two DB updates and one insert with one button - php

I have been fighting with this. Hope this helps others as well. I have a page for an invoice display, it populates and displays perfectly, I want to do major DB changes with the "Pay" button.
If there is an OrderIn_id, it should update the order_instate column of paid to "Yes", or if there is an OrderOut_id it should update the order_outstate column of paid to "Yes", there can be an instance where there is one or the other Id's or could have both. Then it inserts values into an invoice table.
The insert works perfectly, I am not getting any error messages, and it goes to the next page as if it all works, but it does NOT update the order tables to paid = "Yes", it keeps the field the same. Can you advise me of what I may not be seeing in this code. This is the php code that is called when the submit button is pressed.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($row['orderIn_id'])) {
$orderIn_id = $row['orderIn_id'];
$ip_id = $row['ip_id'];
$orderIn_quantity = $row['orderIn_quantity'];
$orderIn_total = $row['orderIn_total'];
$orderIn_paid = "Yes";
$changeVal="UPDATE order_instate
SET user_id = '$user_id', ip_id = '$ip_id', orderIn_quantity = '$orderIn_quantity', orderIn_total = '$orderIn_total',
orderIn_paid = '$orderIn_paid'
WHERE orderIn_id = '$orderIn_id'; " ;
$changeCheck=mysqli_query($dbhandle, $changeVal)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update was successful.<br /></span>";
}
if(isset($row2['orderOut_id'])) {
$orderOut_id = $row2['orderOut_id'];
$op_id = $row2['op_id'];
$orderOut_quantity = $row2['orderOut_quantity'];
$orderOut_total = $row2['orderOut_total'];
$orderOut_paid = "Yes";
$changeVals="UPDATE order_outstate
SET user_id = '$user_id', op_id = '$op_id', orderOut_quantity = '$orderOut_quantity', orderOut_total = '$orderOut_total',
orderOut_paid = '$orderOut_paid'
WHERE orderOut_id = '$orderOut_id'; " ;
$changeCheck2=mysqli_query($dbhandle, $changeVals)
or die(mysqli_error($dbhandle));
}
if (mysqli_affected_rows($dbhandle) == 1) {
echo "<span class = 'errorlog'><br />The Order update for out of state was successful. <br /></span>";
}
$invoice_total = 0;
$invoice_total = $gtotal;
$invoice_shipped = "No";
$add ="INSERT INTO invoice(user_id, invoice_total, invoice_shipped)
VALUES ('$user_id', '$invoice_total', '$invoice_shipped')";
$addCheck=mysqli_query($dbhandle, $add)
or die(mysqli_error($dbhandle));
if($addCheck == NULL){
echo "<span class = 'errorlog'><br />Your Payment was not successful. Please try again. <br /></span>";
} else {
header("location: userOrders.php");
}
}
?>

Related

PHP/mySQLi update values where user exists

We'll get to the point...
I have a simple form (2 of them) that relies off the previous filled out.
The intention of these forms are to sign, post to db, validate email. After the user validates their email their permission will change to be able to see the next form.
These forms work great, and everything is functional in exception to this last bit.
I am having difficulty with the form applying the values to the db table when there is existing user.
What I would like to do is only have it update the keys for that user where users session-ed API key =$API AND form_ica_initials is NULL in the roster table. If it does then will INSERT INTO
Here is what I have cleaned up. (originally wrote for the first phase of the forms to be filled out, trying to tweak to work for last half of forms)
if (empty($_POST['initials'])) { $error[] = 'You must enter your initials in every box below.'; }
else { $initials = $_POST['initials']; }
$API = $_SESSION['API'];
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API ='$API'";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (!$result_verify_form) {
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_form) == 0) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE `roster`
(
`fullname`, `form_ica_initials`, `form_icaauth`,`form_ica_ip`
)
VALUES (
'$fullname', '$initials', '$form_icaauth','$DOCSIGNEDBYIP'
)
";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) {
...
echo '<br><center><div class="success">...</div>';
}
else {
echo '<center><div class="error">...</div></center>';
}
}
else {
echo '<center><div class="warning" >...</div></center>';
}
}
else {
echo '<center><div class="info"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div></center>';
}
mysqli_close($dbc); //Close the DB Connection
}
If I change the if (mysqli_num_rows($result_verify_form) == 0) { to ==1 It will post the values to the table by creating a new record, and not update the existing users fields as specified. However, by doing that it will circumvent the errors that I have structured.
I know my way around PHP a bit... but having difficultly with this one
I was able to get it to work with the following.
if (empty($error)) {
$query_verify_form = "SELECT * FROM roster WHERE API='$API' AND form_ica_initials IS NULL";
$result_verify_form = mysqli_query($dbc, $query_verify_form);
if (mysqli_num_rows($result_verify_form) == 1) {
$form_icaauth = md5(uniqid(rand(), true));
error_reporting(E_ALL);
$query_insert_user = "UPDATE roster SET fullname='$fullname', form_ica_initials='$initials', API='$API', form_icaauth='$form_icaauth', form_ica_ip='$DOCSIGNEDBYIP'";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo '<center><div class="error">Query Failed </div></center>';
}
First I had to change if (mysqli_num_rows($result_verify_form) == 1) from 0 to 1 to return Yes we've found that record.
I then had to change the INSERT INTO ... VALUES to UPDATE ... SET. I added also added AND form_ica_initials IS NULL to validate that the user hasn't completed this form yet. IF they have, then we'd prompt with a message to check their email. If they havent then we'd run the UPDATE

How to update multiple records in MySQL?

I am trying to pull records from a table and update one filed in them. I am able to pull the records and create the form, however the update part is not working.
The code below is above my HTML section.
<?php require_once('../Connections/connect.php'); ?>
<?php
session_start();
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they log in.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}
$MM_restrictGoTo = "sorry.php";
if (!((isset($HTTP_SESSION_VARS['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $HTTP_SESSION_VARS['MM_Username'], $HTTP_SESSION_VARS['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $HTTP_SERVER_VARS['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?>
<?php
$col_points = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
$col_points = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_points = sprintf("SELECT cam_registered_tbl.team_id_num, cam_registered_tbl.wins, cam_registered_tbl.losses, cam_registered_tbl.points, cam_teams_tbl.team_name, cam_registered_tbl.registered_id_num FROM cam_registered_tbl, cam_teams_tbl WHERE cam_registered_tbl.tournament_id_num=%s AND cam_teams_tbl.team_id_num=cam_registered_tbl.team_id_num", $col_points);
$points = mysql_query($query_points, $camsports) or die(mysql_error());
$row_points = mysql_fetch_assoc($points);
$totalRows_points = mysql_num_rows($points);
$col_tournament = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
$col_tournament = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_tournament = sprintf("SELECT cam_tournaments_tbl.tournament_name FROM cam_tournaments_tbl WHERE cam_tournaments_tbl.tournament_id_num=%s", $col_tournament);
$tournament = mysql_query($query_tournament, $camsports) or die(mysql_error());
$row_tournament = mysql_fetch_assoc($tournament);
$totalRows_tournament = mysql_num_rows($tournament);
?>
<?php
//This loops through all the records that have been displayed on the page.
for ($index = 0; $index <= $index_count; $index++) {
/*
This part sets a variable with the names we created in the first section.
We start with 0 and go until the number saved in the $index_count variable.
*/
$varregistered_id_num = 'registered_id_num'.$index;
$varteam_name = 'team_name'.$index;
$varwins = 'wins'.$index;
$varlosses = 'losses'.$index;
$varpoints = 'points'.$index;
/*
This is the variable variable section. We take the value that was assigned
to each name variable. For example the first time through the loop we are
at the record assigned with SubmissionID0. The value given to SubmissionID0
is set from the first section. We access this value by taking the variable
variable of what SubmissionID0 is.
*/
$registered_id_numvalue = $$varregistered_id_num;
$team_namevalue = $$varteam_name;
$winsvalue = $$varwins;
$lossesvalue = $$varlosses;
$pointsvalue = $$varpoints;
//Update the database
$sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',".
"losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
$result = mysql_query($sql);
//If the link was marked approved set the value of the Approved field
if ($goto == '1') {
$insertGoTo = "menu.php";
header(sprintf("Location: %s", $insertGoTo));
}
}
?>
This code is in the body section
<div align="center">
<p><font size="4"><?php echo $row_tournament['tournament_name']; ?></font></p>
</div>
<?php
//Initialize counter variables
$index = 0;
$index_count = 0;
echo "<form method=post action=$PHP_SELF>\n";
echo "<table>\n";
echo "<tr><td><b>Team</b></td>".
"<td><b>Points</b></td></tr>\n";
/*
Assuming we already have retrieved the records from the database into an array setting
$myrow = mysql_fetch_array(). The do...while loop assigns a value to the $xstr variable
by taking the name and concatenating the value of $index to the end starting with 0. So
the first time through the loop $SubmissionIDStr would have a value of SubmissionID0 the
next time through it would be SubmissionID1 and so forth.
*/
do {
$registered_id_numStr = registered_id_num.$index;
$team_nameStr = team_name.$index;
$pointsStr = points.$index;
//This section would print the values onto the screen one record per row
printf("<tr><td><input type=hidden name=%s value=%s>%s</td>
<td><input type=text name=%s value=%s size='5'></td></tr>\n",
$registered_id_numStr, $row_points["registered_id_num"], $row_points["team_name"], $pointsStr, $row_points["points"]);
//Increase counter values by 1 for each loop
$index++;
$index_count++;
} while ($row_points = mysql_fetch_array($points));
// I also had to create an index count to keep track of the total number of rows.
echo "<INPUT TYPE=hidden NAME=counter VALUE=$index_count>\n";
echo "<INPUT TYPE=hidden NAME=goto VALUE='1'>\n";
echo "<INPUT TYPE=submit></form>\n";
echo "</table>";
?>
Any help would be greatly appreciated.
You are doing it right - I don't know of any better approach for your case than running update in for loop. What you should do is to enclose this in a transaction:
mysql_query("start transaction");
for ($index = 0; $index <= $index_count; $index++) {
...
$sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',"."losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
$result = mysql_query($sql);
if (!$result) { // you possibly should do some error checking
mysql_query("rollback"); // cancel the transaction
//print error
exit(0);
}
...
}
mysql_query("commit"); // commit the transaction
If you don't use the transaction, you might end up with just some of the records updated, which will leave the database in inconsistent state. Transaction is very important here - with it, all of the records are updated, or none.
Make sure you use the InnoDB engine, in MyISAM engine the transactions do not work.
I didn't read the whole code, but if you have multiple records and you wish to update the same field (with the same value), you can achieve it like this:
UPDATE mytable SET filed = '$value' WHERE id IN (1,2,3,4,5)
if you have an array with ids, you can do it like this:
$ids = implode(',',$array_ids);
UPDATE mytable SET field = '$value' WHERE id IN ('$ids')
BUT
If the values are different for each id, just run a loop that updates values for each row.

i need to insert some text from textarea and then update it in db as i type or save it using php ajax mysql

i have this code to save note from text area
this is my post-note.php file
<?php
include('connect.php');
if(isset($_POST['note_title'])){
$note_title = $_POST['note_title'];
$note_description = $_POST['note_description'];
$login_user_id = $_SESSION['user_id'];
$errors = array();
if($note_title == ""){
$errors['note_title'] = 'fine';
}else{
$errors['note_title'] = 'fine';
}
if($note_description == ""){
$errors['note_description'] = '<span class="note_description">Please enter something</span>';
}elseif(strlen($note_description) < "3"){
$errors['note_description'] = '<span class="note_description">your note is too short</span>';
}else{
$errors['note_description'] = 'fine';
}
if($errors['note_title'] && $errors['note_description'] == 'fine'){
$Query = "INSERT INTO notes (note_title, login_user_id, note_description, is_private)
VALUE('$note_title', '".$login_user_id."', '".$note_description."','0')";
if (!mysql_query($Query)){
die('Error: ' . mysql_error());
}
$errors['done'] = 'done';
unset($_POST['note_title']);
unset($_POST['note_description']);
}
}
echo json_encode($errors);die;
?>`
i want to insert first time as new row then want to update that row in database
In notes table, add a column id (if its not already there).
On create note page use above code.
On update note page pass id field of that note in $_POST.
So if isset($_POST['id']) write an UPDATE note ... WHERE id=$_POST['id'].
This will update already created note or will insert if its a new note.
filter user inputs before inserting though

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

How do I check if a field in my mySQL database is empty in PHP

I would like to know how to how to check if a field (column) is empty for a specific user.
I have connected successfully to a mySQL database, I have entered a user and I have fields that are empty. I have a post form that allows users to enter information. Based on whether other fields are empty, I would like them to fill accordingly. I would like to use logic to determine whether a field is empty or not. I am using the following:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(trim($_POST['listing_link']) == '') {
}
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link1) && empty($listing_link2)) {
$listing_link2 = $_POST['listing_link'];
$listing_link2 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link2`='$listing_link2'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link2) && empty($listing_link3)) {
$listing_link3 = $_POST['listing_link'];
$listing_link3 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link3`='$listing_link3'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link3) && empty($listing_link4)) {
$listing_link4 = $_POST['listing_link'];
$listing_link4 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link4`='$listing_link4'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link4) && empty($listing_link5)) {
$listing_link5 = $_POST['listing_link'];
$listing_link5 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link5`='$listing_link5'
WHERE `email`='$emailstring'";
}
$result = mysql_query($query);
}
?>
This code checks whether there is anything entered by the user when they hit the button for the "listing_link". If not, then nothing happens. If something is entered, then it will check to determine if any of the other fields are filled (listing_link1, listing_link2...listing_link5). The $listing_link1 - 5 variables are supposed to take on the information.
I cannot get the other else ifs to run except for:
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
And continually running the code by hitting the button for the form just replaces the listing_link1 variable with the newly entered information.
Perhaps there is something wrong with the logic written here. Please help if you can.
You're not defining $listing_link1 until after you've checked to see if it's empty:
else if(empty($listing_link1))
{
$listing_link1 = $_POST['listing_link'];
Flip 'em around:
$listing_link1 = $_POST['listing_link'];
if(empty($listing_link1))
{
If I got you right, this would solve your woes:
$empty = 0;
for($i=1; $i<=5; $i++){
$varname = "listinglink$i";
if(empty($$varname)){
$empty = $i;
break;
}
}
if($empty > 0){
$update_field = "listinglink{$empty}";
$update_data = $_POST['listing_link'];
mysql_query("UPDATE users SET `$update_field`='$update_data'
WHERE email='$emailstring'");
}
What I do there is spin a loop to check which one is the first empty *listing_link* and as soon as I find it, set some variable to its number and quit the loop. From there it's pretty much simple.
What this does: $$varname = 1; is that it takes the value of $varname and tries to use it as a variable name, for example:
$test = "groovy.";
$varname = "test";
echo $$varname; // eqivalent to "echo $test"
Fun technique :)

Categories