Update multiple SQL records using one PHP/MySQLi query - php

Is it possible to update multiple records in one MySQLi query?
There are 4 records to be updated (1 for each element level) when the submit button is clicked.
The results are posted to a separate PHP page which runs the query and returns the user back to the edit page. elementid is 1,2,3,4 and corresponds with Earth, wind, fire, water. These never change (hence readonly or hidden)
<form id="edituser" name="edituser" method="post" action="applylevelchanges.php">
<fieldset>
<legend>Edit Element Level</legend>
<?php
while($userdetails->fetch())
{?>
<input name="clientid" id="clientid" type="text" size="8" value="<?php echo $clientid; ?>" hidden />
<input name="elementid" id="elementid" type="text" size="8" value="<?php echo $elementid;?>" hidden />
<input name="elemname" id="elemname" type="text" size="15" value="<?php echo $elemname; ?>" readonly />
<input name="elemlevel" id="elemlevel" type="text" size="8" required value="<?php echo $elemlevel; ?>" /></br>
</br>
<?php }?>
</fieldset>
<button type="submit">Edit Student Levels</button>
</form>
And the code to apply the changes
<?php
if (isset($_POST['clientid']) && isset($_POST['elementid']) && isset($_POST['elemname']) && isset($_POST['elemlevel'])) {
$db = createConnection();
$clientid = $_POST['clientid'];
$elementid = $_POST['elementid'];
$elemname = $_POST['elemname'];
$elemlevel = $_POST['elemlevel'];
$updatesql = "update stuelement set elemlevel=? where clientid=? and elementid=?";
$doupdate = $db->prepare($updatesql);
$doupdate->bind_param("iii", $elemlevel, $clientid, $elementid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: edituserlevel.php");
exit;
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
}

Related

How to display information of a selected user from a database for editing

I Am trying to edit user details from a database. I have queried the database and stored the info in $row, but each time I try to echo the details I get the following error: Trying to access array offset on the value of type null in
C:\xampp\htdocs\merchant\admin\edituserhis.php
I seem not to know what I am doing wrong in the SQL statement, I have checked the Variable $id and its working well.
<div class="quotes">
<?php
$con = mysqli_connect("localhost","root","","merchant_db");
$id = $_REQUEST['username'];
$query = "SELECT * from user_trans where userid='".$id."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
<?php echo $row['userid']; ?>;
<form name="form" method="post" action="userprofile.php">
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $row['userid'];?>" />
<p><input type="text" name="balance" placeholder="Enter Amount" required value="<?php echo $row['description'];?>" /></p>
<p><input name="submit" type="submit" value="Credit" /></p>
</form>
</div>

Editing SQL Database using PHP

While editing a specific record using PHP code given below, all records in the database are edited simultaneously to the some garbage values. Here "db" is the Database. I am new to PHP and SQL. Please help
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks, $isdate, $issuedto, $returndate)
{
?>
<!DOCTYPE HTML PUBLIC >
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<form action="edit.php" method="post">
<div>
<p><strong>Report No.:</strong> <?php echo $reportno; ?></p>
<strong>Date of receipt: *</strong> <input type="date" name="dateofreceipt" value="<?php echo $dateofreceipt; ?>"/><br/>
<strong>Report Title: *</strong> <input type="text" name="title" value="<?php echo $title; ?>"/><br/>
<strong>Report Type: *</strong> <input type="text" name="type" value="<?php echo $type; ?>"/><br/>
<strong>Issuing agency: *</strong> <input type="text" name="issuingagency" value="<?php echo $issuingagency; ?>"/><br/>
<strong>Marked to: *</strong> <input type="text" name="markedto" value="<?php echo $markedto; ?>"/><br/>
<strong>Date: *</strong> <input type="date" name="date" value="<?php echo $date; ?>"/><br/>
<strong>Remarks: *</strong> <input type="text" name="remarks" value="<?php echo $remarks; ?>"/><br/>
<strong>Issuing Date: *</strong> <input type="date" name="isdate" value="<?php echo $isdate; ?>"/><br/>
<strong>Issued To: *</strong> <input type="text" name="issuedto" value="<?php echo $issuedto; ?>"/><br/>
<strong>Return Date: *</strong> <input type="date" name="returndate" value="<?php echo $returndate; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$reportno = $_POST['reportno'];
$dateofreceipt = mysql_real_escape_string(htmlspecialchars($_POST['dateofreceipt']));
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$issuingagency = mysql_real_escape_string(htmlspecialchars($_POST['issuingagency']));
$markedto = mysql_real_escape_string(htmlspecialchars($_POST['markedto']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
$isdate = mysql_real_escape_string(htmlspecialchars($_POST['isdate']));
$issuedto = mysql_real_escape_string(htmlspecialchars($_POST['issuedto']));
$returndate = mysql_real_escape_string(htmlspecialchars($_POST['returndate']));
//renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date,$remarks, $isdate, $issuedto, $returndate, $error);
// save the data to the database
mysql_query("UPDATE `db` SET `Report No.`='[$reportno]',`Date of receipt`='[$dateofreceipt]',`Report Title`='[$title]',`Report Type`='[$type]',`Issuing agency`='[$issuingagency]',`Marked to`='[$markedto]',`Date`='[$date]',`Remarks`='[$remarks]',`Issuing date`='[$isdate]',`Issued to`='[$issuedto]',`Return Date`='[$returndate]' WHERE `Report No.`= '$id'")
// once saved, redirect back to the view page
header("Location: view.php");
}
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM db WHERE `Report No.`= '$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$reportno = $row['Report No.'];
$dateofreceipt = $row['Date of receipt'];
$title= $row['Report Title'];
$type= $row['Report Type'];
$issuingagency= $row['Issuing agency'];
$markedto= $row['Marked to'];
$date= $row['Date'];
$remarks=$row['Remarks'];
$isdate= $row['Issuing date'];
$issuedto= $row['Issued to'];
$returndate= $row['Return Date'];
// show form
renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks ,$isdate, $issuedto, $returndate, '');
}
?>
Try this query for updation. Also dont forget to add semicolons after statements. Use mysqli_* Functions instead of mysql_*
mysqli_query("UPDATE `db` SET `Date of receipt`='$dateofreceipt',`Report Title`='$title',`Report Type`='$type',`Issuing agency`='$issuingagency',`Marked to`='$markedto',`Date`='$date',`Remarks`='$remarks',`Issuing date`='$isdate',`Issued to`='$issuedto',`Return Date`='$returndate' WHERE Report No = $reportno");
Several issues here:
The mysql api in PhP is deprecated. Don't bet on it working for longer. Use the mysqli api instead.
In your query the "where 1 part is completly superflous. 1 means true and where 1 means all records, at which point you can leave the WHERE out completly. You probably wanted to use WHERE somekey = 1, which is different.
try this
mysql_query("UPDATE db SET Report No.=".'$reportno'.",Date of receipt=."'$dateofreceipt'.",Report Title=."'$title'.",Report Type=."'$type'.",Issuing agency=."'$issuingagency'.",Marked to=."'$markedto'.",Date=."'$date'.",Remarks=."'$remarks'.",Issuing date=."'$isdate'.",Issued to=."'$issuedto'.",Return Date=."'$returndate'." WHERE Report No.= ."'$id'."")

PHP MYSQL Next AND Previous row

Basically I have a table with data, and I have a form with boxes and stuff, and what I am trying to do is when the I click on the next or previous button, it will take the next record from the database. I can do the first and the last record, but I cant manage to figure the in between. this what I have.
$sql="SELECT * FROM Emails where ID > 1 ORDER BY UserEmail LIMIT 1";
if ($result=mysqli_query($connection,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
while( $row = mysqli_fetch_array( $result ) )
{
$Email_Field = $row['UserEmail']; //primary key
$Name_Field = $row['UserName'];
$UserTel = $row['UserTel'];
$Drop_Down = $row['Drop_down'];
$MessageType = $row['MessageType'];
$Comments = $row['Comments'];
$SubjectOther = $row['SubjectOther'];
$Check = $row['Request'];
}
<form method="POST" action="Controller_leads.php">
<p><strong>What kind of comment would you like to send?</strong></p>
<input type="radio" <?php if ($MessageType == "Complaint") echo "checked"; ?> name="MessageType" value="Complaint">Complaint
<input type="radio" <?php if ($MessageType == "Problem") echo "checked"; ?> name="MessageType" value="Problem">Problem
<input type="radio" <?php if ($MessageType == "Suggestion") echo "checked"; ?> name="MessageType" value="Suggestion">Suggestion
<br>
<p><strong>What about us do you want to comment on?</strong></p>
<select name="Drop_Down" size="1">
<option value ="Web Site" <?php if ($Drop_Down == "Web Site") echo selected ?>>Web Site</option>
<option value ="Office Hours" <?php if ($Drop_Down == "Office hours") echo selected ?>>Office Hours</option>
<option value ="Pamphlet" <?php if ($Drop_Down == "Pamphlet") echo selected ?>>Pamphlet</option>
</select>
Other: <input type="text" size="26" maxlength="256" name="SubjectOther" value="<?php echo $SubjectOther ?>">
<p><strong>Enter your comments in the space provided below:</strong></p>
<textarea name="Comments" rows="5" cols="42"><?php echo $Comments;?></textarea><br><br>
<strong>Tell us how to get in touch with you:</strong><br><br>
<table>
<tr><td width="45"> Name </td> <td><input type="text" size="35" maxlength="256" name="UserName" value="<?php echo $Name_Field ?> "></td></tr>
<tr><td width="45"> E-mail </td> <td><input type="text" size="35" maxlength="256" name="UserEmail" value="<?php echo $Email_Field ?>"></td></tr>
<tr><td width="45"> Telephone</td> <td><input type="text" size="35" maxlength="256" name="UserTel" value="<?php echo $UserTel ?>"></td></tr>
</table>
<br>
<input type="checkbox" name="Check" <?php if ($Check == "Contact Requested") echo checked; ?> value="Contact Requested">Please contact me as soon as possible regarding this matter
<br><br>
<input type="submit" value="First" name="first">
<input type="submit" value="Next" name="next">
<input type="submit" value="Previous" name="previous">
<input type="submit" value="Last" name="last"> code here
Try adding an offset to the query. On each next click add one to $offset, on each previous, subtract one from offset. Then, include offset in the query like this:
# get the current offset
# initial value
$offset = 1;
# if we have an offset from a previous or next click, use that
if (isset($_POST['offset'])) {
# validate this input to protect against sql injection
if (is_int($_POST['offset'])) {
$offset = $_POST['offset'];
}
# now that we have our current value, see if we need to get the next or previous
if ($_POST['submit']=="Next") {
# next, add one offset
$offset++;
} else if ($_POST['submit']=="Previous") {
# previous, go back one if we are greater than one
if ($offset > 1) {
$offset--;
}
}
}
# query time, give me one result (LIMIT 1), staring at record $offset
$sql = "select SELECT * FROM Emails where UserEmail > 1
ORDER BY UserEmail LIMIT 1, $offset";
In your form add this:
<input type="hidden" name="offset" value="<?php echo $offset; ?>">
On a different note, UserEmail > 1 seems weird, but I don't know your data.

Table not updating after mysql query

I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }

MySQL/PHP: Insert form array into database?

I am a PHP newbie having a problem inserting an array from a form into the database using foreach statement.
I am trying to create a form that accepts Score, Grade and Comment for each subject. However,only the last subject gets inserted into the database. The list of subjects is loaded from previously registered subjects (I have no problem with that). My problem is getting all the subjects to save back to database.
This is the form i use:
<legend>ENTER RESULTS:</legend>
<input type="hidden" name="results[]" value= "<?php foreach ($subjects as $subject):?>
<ul>
<li> <input type="text" name="subject_name" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
<?php endforeach; ?>
<input type="hidden" name="student_id" value="<?php
htmlout($student_id); ?>
</fieldset>
This is the php code i use:
if (isset($_GET['result']))
{
try
{
$sql = 'INSERT INTO results SET
student_id = :student_id,
subject_name = :subject_name,
subject_grade = :subject_score,
subject_grade = :subject_grade,
subject_comment = :subject_comment';
$s = $pdo->prepare($sql);
foreach ($_POST['results'] as $result)
{
$s->bindValue(':student_id',$_POST['student_id']);
$s->bindValue(':subject_name', $_POST['subject_name']);
$s->bindValue(':subject_score', $_POST['subject_score']);
$s->bindValue(':subject_grade', $_POST['subject_grade']);
$s->bindValue(':subject_comment', $_POST['subject_comment']);
$s->execute();
}
}
catch (PDOException $e)
{
$error = 'Could not Register the Student for the Subjects, Please try again'.$e->GetMessage();
include 'error.html.php';
exit();
}
echo 'Success';
you can use form element in array like subject_score[]
your form should be like
foreach
<input type="text" name="subject_name[]" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score[]" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade[]" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment[]" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
endforeach
then you can collect those value like below
foreach($_POST['subject_name'] as $key=>$val){
//val will hold subject name
}

Categories