PHP for loop not displaying correct data - php

I have this PHP code/form:
<form method="post" action="tickets_report2.php">
<table width="800" border="0" cellspacing="5" cellpadding="5">
<tr>
<td><strong>Select</strong></td>
<td><strong>Company</strong></td>
</tr>
<?php
$sql="SELECT * from customer ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$counter=0;
while($result=mysql_fetch_array($rs)) {
$counter++;
echo '<tr>
<td><input type="checkbox" value="'.$result["sequence"].'" name="checkbox'.$counter.'" /></td>
<td>'.$result["company"].'</td>
</tr>';
}
echo '<input type="hidden" name="counter" value="'.$counter.'" />';
?>
</table>
<input type="submit" name="submit" value="Next" />
</form>
and on the form action page:
<table width="800" border="0" cellspacing="5" cellpadding="5">
<tr>
<td><strong>Company</strong></td>
</tr>
<?php
for($i=1; $i<=$_POST["counter"]; $i++) {
if($_POST["checkbox$i"]) {
$sql="SELECT * from customer where sequence = '".$i."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<tr>
<td>'.$result["company"].'</td>
</tr>';
}
}
?>
</table>
lets say i check the checkbox on the form for the row in the database with sequence of 278, the SQL Query should say SELECT * from customer where sequence = '278' but its showing SELECT * from customer where sequence = '1'
i think its using the counter rather than the customer sequence
what do i need to change to get this working correctly so it selected the correct customer(s)

On the form action page it should read:
if($_POST["checkbox$i"]) {
$sql="SELECT * from customer where sequence = '".$_POST["checkbox$i"]."' ";
Note: sanitize your inputs.

form page:
<form method="post" action="tickets_report2.php">
<table width="800" border="0" cellspacing="5" cellpadding="5">
<tr>
<td><strong>Select</strong></td>
<td><strong>Company</strong></td>
</tr>
<?php
$sql="SELECT * from customer ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$counter=0;
while($result=mysql_fetch_array($rs))
{
$counter++;
echo '<tr>
<td><input type="checkbox" value="'.$result["sequence"].'" name="checkbox['.$counter.']" /></td>
<td>'.$result["company"].'</td>
</tr>';
}
?>
</table>
<input type="submit" name="submit" value="Next" />
</form>
action page:
<table width="800" border="0" cellspacing="5" cellpadding="5">
<tr>
<td><strong>Company</strong></td>
</tr>
<?php
foreach($_POST["checkbox"] as $value)
{
$sql="SELECT * from customer where sequence = '".$value."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<tr>
<td>'.$result["company"].'</td>
</tr>';
}
?>
</table>

Related

increment variable on submit to update mysql query

I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>

Multiple records updating in single query using PHP and MySQL

Can any one help on this issue.When i'm trying to updating multiple record using catid(it contain same catid one or more) it is not updating results.
Below is the code
enter code here
<?php
//select a database to work with
$selected = mysql_select_db("db_name",$cnn) or die("Could not select examples");
$sql="SELECT *
FROM `plannedbudgetstbl`
LEFT JOIN budget_categories ON plannedbudgetstbl.cat_id = budget_categories.cat_id
WHERE programid ='".$id."'";
$result=mysql_query($sql);
// Count table rows
$count=mysql_num_rows($result);
?>
<form name="form1" method="post" action="">
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr>
<td align="center"><strong>budget</strong></td>
</tr>
<?php
// Check if button name "submit" is active, do this
if (isset($_POST['submit'])) {
$budget = $_POST['budget'];
for($i=0;$i<$count;$i++){
$sql1="UPDATE plannedbudgetstbl SET budget='".$budget[$i]."' WHERE programid = '".$id[$![enter image description here][1]i]."'and cat_id='".$id[$i]."'";
$result1=mysql_query($sql1);
}
}
if(isset($result1)){
header("location:budget-dispaly1.php");
}
?>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><?php $id[]=$rows['cat_id']; ?><?php echo $rows['cat_id']; ?></td>
<td align="center"><input name="budget[]" type="text" id="budget" value="<?php echo $rows['budget']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center"><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
Here is the update output

Unlocked Forum Post saying it's locked?

All right, sorry for so many posts. Anyway, I have created an entire file of code; view_topic.php, that is just showing a forum post. I know it is messy and not in mysqli, I will be rewriting the ENTIRE code, once I finish this page. Anyway, on to the problem. When you visit any topic, locked or unclicked, it will ALWAYS say, "Sorry, this post is locked." There are no error messages. I have spent all day trying to find the error in my code, and I have turned to the internet for guidance. Here is the whole code, tell me if you need anything else:
<?php
require_once 'core/init.php';
// get value of id that sent from address bar
$id=$_GET['id'];
$sql="SELECT * FROM `forum_question` WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
$thisql = "SELECT `locked` FROM `forum_question` WHERE `id`='$id'";
$mythisql = mysql_query($thisql);
$mythisql1 = mysql_fetch_array($mythisql);
if ($mythisql1 === false) { // add this check.
die('Invalid query: ' . mysql_error());
}
?>
<table width="700" align="center" class="outer">
<tr>
<td><table width="100%">
<tr>
<td class="back">Back to Forum Home?</td>
</tr>
<tr>
<td><center><h3>
<?php
echo $rows['topic'];
?>
</h3></center></td>
</tr>
<tr>
<td align="right"><?php
if ($user_data['username'] === $rows['name']) {
?>
<form action="lock.php" method="post">
Lock? <input type="checkbox" name="lock" value="1" />
<input type="hidden" name="id" value="<?php echo $rows['id']; ?>" />
<input type="submit" value="Submit">
</form>
<?php
} ?>
</td>
</tr>
<tr>
<td><?php echo $rows['detail']; ?></td>
</tr>
<tr>
<td class="forumreply">By <?php echo $rows['name']; ?>, On <?php echo $rows['datetime']; ?>
</tr>
</table></td>
</tr>
</table>
<BR>
<?php
$tbl_name2="forum_answer"; // Switch to table "forum_answer"
$sql2="SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2=mysql_query($sql2);
while($rows=mysql_fetch_array($result2)){
?>
<table width="700" align="center" class="outer">
<tr>
<td><table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr><tr>
<td><?php echo $rows['a_answer']; ?></td>
</tr>
<td class="forumreply">By <?php echo $rows['a_name']; ?>, On <?php echo $rows['a_datetime']; ?></td>
</tr>
</table></td>
</tr>
</table><br>
<?php
}
$sql3="SELECT view FROM `forum_question` WHERE id='$id'";
$result3=mysql_query($sql3);
$rows=mysql_fetch_array($result3);
$view=$rows['view'];
// if have no counter value set counter = 1
if(empty($view)){
$view=1;
$sql4="INSERT INTO `forum_question`(view) VALUES('$view') WHERE id='$id'";
$result4=mysql_query($sql4);
}
// count more value
$addview=$view+1;
$sql5="update `forum_question` set view='$addview' WHERE id='$id'";
$result5=mysql_query($sql5);
?>
<?php
if (logged_in() === true) {
if ($mythisql1['locked']===0) {
?>
<BR>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="add_answer.php">
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="a_name">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td valign="top"><strong>Reply</strong></td>
<td valign="top">:</td>
<td><textarea name="a_answer" cols="45" rows="3" id="a_answer"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input name="id" type="hidden" value="<?php echo $id; ?>"></td>
<td><input type="submit" name="submit" value="Submit"> <input type="reset" name="Submit2" value="Reset"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
} else {
echo "Sorry, this post is locked.";
}
}
ob_end_flush();
?>
If anyone can figure out my problem, I will be eternally grateful. Thanks.
I can not see you data so it's a guess
use onyl ==0 not ===0
if (logged_in() === true) {
if ($mythisql1['locked']==0) {
?>
or if $mythisql1['locked'] is a string
if (logged_in() === true) {
if ($mythisql1['locked']=='0') {
?>
This code has multiple problems. SQL Injection is one. This is a bad case alone. Also, when updating the views counter: do it properly in SQL! update forum_question set view=view+1 WHERE id='".mysql_real_escape_string($id)."'". This would eliminate race conditions... Also, the view column is not string (I hope), so you don't need the single quotes around the value... –

Javascript add MySQL data when checkbox is ticked

I am currently using this javscript and PHP code
<script>
function add(total)
{
form2.thetotal.value = document.forms["form1" + total].total.value;
}
</script>
<form name="form2">
<table width="800" border="0" cellspacing="0" cellpadding="10" style="position:fixed; z-index:-999; background-color:#FFF;">
<tr bgcolor="#eeeeee">
<td> </td>
<td colspan="2" width="50%"><strong>Total: </strong><input type="text" name="thetotal" id="thetotal" size="20" value="0" /></td>
<td colspan="2" width="50%"><strong>VAT:</strong> </td>
</tr>
<tr bgcolor="#eeeeee">
<td width="5%"> </td>
<td width="20%"><strong>Invoice Number</strong></td>
<td width="35%"><strong>Company</strong></td>
<td width="20%"><strong>Date</strong></td>
<td width="20%"><strong>Total</strong></td>
</tr>
</table>
</form>
<form name="form1">
<table width="800" border="0" cellspacing="0" cellpadding="10">
<?php
$sql="SELECT * from billing_pdf_archive order by invoice_number ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
$counter++;
$sql2="SELECT * from customer where sequence = '".$result["customer_sequence"]."' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
$result2=mysql_fetch_array($rs2);
$sql3="SELECT * from reseller where sequence = '".$result["reseller_sequence"]."' ";
$rs3=mysql_query($sql3,$conn) or die(mysql_error());
$result3=mysql_fetch_array($rs3);
if($result["customer_sequence"] != '0')
{
$company = $result2["company"];
}
elseif($result["reseller_sequence"] != '0')
{
$company = '<strong>Reseller: </strong>'.$result3["company"];
}
$total = $result["total"];
echo '<tr>
<td width="5%"><input type="checkbox" name="check" id="check" onclick=\'add('.$total.');\' /></td>
<td width="20%">'.$result["invoice_number"].'</td>
<td width="35%">'.$company.'</td>
<td width="20%">'.$result["datetime"].'</td>
<td width="20%">£'.$result["total"].'</td>
</tr>';
}
?>
</table>
</form>
so as you can see it is selecting from the MySQL database and i am trying to make it so when one of the checkboxes is ticked it adds the total into the "thetotal" text field (in form 2) but it is just leaving that box as zero - any ideas on what i could do?
You did not specify the total field for form 1, then it raised javascript error, it wont work.
Check it out
<script>
function add(total)
{
form2.thetotal.value = total + parseFloat(document.form1.formtotal.value);
}
</script>
<form name="form1">
<!-- replace field name formtotal with anything that you want-->
<!-- replace field value with anything that you get from your mysql result-->
<input type="text" name="formtotal" id="formtotal" value="10" />
</form>
Here is how you can do it (assuming total is int and not float):
<script>
function add(total, this_chk_bx)
{
//(if its float, use `parseFloat` instead of `parseInt`)
if(this_chk_bx.checked==true){
//add if its checked
var tot_1 = parseInt(form2.thetotal.value);
form2.thetotal.value = tot_1+parseInt(total);
}
else{
//subtract if its unchecked
}
}
</script>
.
in your php, you have to send the checkbox like this:
onclick=\'add('.$total.', this);\'
.

Delete multiple rows by selecting checkboxes using PHP

I want to delete multiple rows from my MYSQL database table. I have created this file to select various links and delete them using checkboxes.
This doesn't seem to delete any row. My data is populated in the table. I guess the problem is with my PHP code. Please check the below code and guide me to get out from this...
<html>
<head>
<title>Links Page</title>
</head>
<body>
<h2>Choose and delete selected links.</h2>
<?php
$dbc = mysqli_connect('localhost','root','admin','sample') or die('Error connecting to MySQL server');
$query = "select * from links ORDER BY link_id";
$result = mysqli_query($dbc,$query) or die('Error querying database');
$count=mysqli_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="3" bgcolor="#FFFFFF">
<strong>Delete multiple links</strong>
</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link ID</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link Name</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link URL</strong>
</td>
</tr>
<?php
while ($row=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox" type="checkbox" value="
<?php echo $row['link_id']; ?>">
</td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_id']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_name']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_url']; ?> </td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" value="Delete">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php
// Check if delete button active, start this
if(isset($_POST['delete']))
{
$checkbox = $_POST['checkbox'];
for($i=0; $i<count($checkbox); $i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM links WHERE link_id='$del_id'";
$result = mysqli_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo '<meta http-equiv="refresh" content="0;URL=view_links.php">';
}
}
mysqli_close($dbc);
?>
</body>
</html>
You should treat it as an array like this,
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Then only, you can take its count and loop it for deletion.
You also need to pass the database connection to the query.
$result = mysqli_query($dbc, $sql);
Yours did not include it:
$result = mysqli_query($sql);
Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as
$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";
Thats one single query to delete them all.
Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
Something that sometimes crops up you may/maynot be aware of
Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE
As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?
If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?
$deleted = $_POST['checkbox'];
$sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

Categories