PHP MYSQL Next AND Previous row - php

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.

Related

Update multiple SQL records using one PHP/MySQLi query

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

Simple form does not get $_POST value and cannot submit

Somehow this takes me a day and still does not solve, I have other forms that works properly. But this one looks perfect but it simply refresh the page after I submit the form.
<form action="" enctype='multipart/form-data' name= 'myForm' id="myForm" method='post'>
<label>
<span>Product Name</span><input id="product_name" value='<?php echo $product_name;?>' type="text" name="product_name" disabled >
</label>
<label>
<span>Retail Price</span> <input name='retail_price' value="<?php echo $retail_price;?>" type='text' id='retail_price' size='10' disabled >
</label>
<label>
<span>Discount (%)</span> <input name='discount' value="<?php echo $discount;?>" type='text' id='discount' size='10'disabled >
</label>
<label>
<span>Details</span><textarea id="details" class="product_details" placeholder="For any other reasons, please provide details here" name="details"></textarea>
</label>
<label>
<span>Reason to Report</span>
<select name='reason' id='reason' class="required">
<option value = '' > </option>
<option value = 'price10' > Product price is higher than $9.9</option>
<option value = 'shelf' > Product is off the shelf</option>
<option value = 'no_fs' > Product does not have free-shipping</option>
<option value = 'reject' > Seller does not deliver products</option>
<option value = 'price_not_match' > Product Price does not match on Upto9 </option>
<option value = 'category' > Product is in wrong category </option>
<option value = 'other' > Other reasons</option>
</label>
<label>
<input name='submit' type='submit' id='button' class="button" value="Submit Report"/>
</label>
</form>
THen This is my php code :
echo 'before';
if (isset($_POST['submit'])) {
echo 'after';
var_dump($_POST);
$con= mysqli_connect("xxxxx.com"," admin","xxxxx","xxxxx") or die(mysqli_error($con));
$details=mysqli_real_escape_string($con,$_POST['details']);
$reason=mysqli_real_escape_string($con,$_POST['reason']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql="INSERT INTO reports (pid,product_name,listing_price,links,discount,retail_price,details,stock_level,reason,report_time,reporter,reporter,ip) VALUES
('$pid','$product_name','$listing_price','$links','$discount','$retail_price','$details','$stock_level','$reason',now(),'$log_username','$ip')";
$query = mysqli_query($con, $sql);
mysqli_insert_id($con);
mysqli_close($con);
header('Location: ' . $_SERVER['HTTP_REFERER']);
echo "successful!";}
The output is: befre
after I added the sql code var_dump($_POST) gives me nothing, so probably the sql code is wrong...

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
}

Simple PHP questions about hiding a input

I want to hide a field of a form when number 1 has been chosen and is loaded in the databse.
The code gives no errors, but the field stays visible with number 0 and 1.
Somehow I can't get it right. It tried the following;
<?php
$query3 = mysql_query("SELECT `status`, `authcode` FROM `auth` ORDER BY `status` ASC LIMIT 1");
while($row3 = mysql_fetch_object($query3)){
?>
<tr>
<td><b>Authcode:</b></td>
<td>
<input name="authcode" type="text" value="<?= $row->authcode; ?>" <?php if($row->status == 0) ?> />
<input name="authcode2" type="hidden" value="<?= $row->authcode; ?>" <?php if($row->status == 1) ?> />
</td>
</tr>
You need to wrap the if around the output you want to be conditionalized on it:
<?php if ($row3->status == 0) { ?>
<input name="authcode" type="text" value="<?= $row3->authcode; ?>" />
<?php }
if ($row3->status == 1) { ?>
<input name="authcode2" type="hidden" value="<?= $row3->authcode; ?>" />
<?php } ?>
You have to put the if statement before:
<?php if ($row->status == 1) ?>
<input name="authcode2" type="hidden" value="<?= $row->authcode; ?>"/>
Agree with Bamar and Pablo.
If you only want the hidden field once (row->status == 1), you could be more precise with something like:
<input name="authcode" type="<?php echo (($row->status == 1)?'hidden':'text') ?>" value="<?php echo $row->authcode; ?>" />
Cheers.

Categories