PHP Error When Submited - php

Im trying to display 2 rows from my database but i want it to be that when i click the 1st row radiobuttons the 1st row updates.. this is not happening ... when i click the 1st row the second row updated .. check it yourself live please ---> http://albsocial.us/seria.php
<?php
include("connect.php");
$query = "SELECT * FROM test ORDER BY `id` DESC LIMIT 2";
$result = mysql_query($query);
echo "<h2>Seria A</h2><hr/>";
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 $home, " - ", $away,"<br/>";
echo "<form action='' method='post'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='radio' name='select' value='1'>1
<input type='radio' name='select' value='X'>X
<input type='radio' name='select' value='2'>2
<input type='submit' name='submit' value='Submit'/>
</form>
";
echo $home, " -> ", $win;
echo "<br/>Barazim -> ", $draw,"<br/>";
echo $away, " -> ", $lose,"<hr/>";
}
$id = isset($_POST['id']) && is_numeric($_POST['id']) ? $_POST['id']:false;
if (isset($_POST) && $_POST['select'] == 1){
$select = $_POST['select'];
$select = $win + $select;
mysql_query("UPDATE test SET win='$select' WHERE id='$id'");
header('Location: ../seria.php');
}else if (isset($_POST) && $_POST['select'] == 'X'){
$select = $_POST['select'];
$select = '1';
$select = $draw + $select;
mysql_query("UPDATE test SET draw='$select' WHERE id='$id'");
header('Location: ../seria.php');
}else if (isset($_POST) && $_POST['select'] == 2){
$select = $_POST['select'];
$select = '1';
$select = $lose + $select;
mysql_query("UPDATE test SET lose='$select' WHERE id='$id'");
header('Location: ../seria.php');
}
?>

the problem is with your button name. you should give each of your button name, a different name from each other so that the server will know which form is being submitted. you could try to give your button name based on id like this :
<input type='submit' name='submit<?php echo $id; ?>' value='Submit'/>
then you could do the conditional statement to see which button is clicked like this :
if ( isset( $_POST['submit$id'] ) ) { }

Your while loop will always leave $id set to the id of the last row in your dataset.
You'll need some way of submitting an id for each row in your form. Then, get that value when you retrieve POST variables.
If you structure things properly, you won't need to do a header redirect.
Also, I suggest moving the isset($_POST) test to it's own if statement, just so none of that code gets executed if nothing has been posted.
Here's how I would rework it:
<?php
include("connect.php");
// if data is submitted, update database
if (!empty($_POST)) {
$id = isset($_POST['id']) && is_numeric($_POST['id']) ? $_POST['id'] : false;
$select = isset($_POST['select'])&&in_array($_POST['select'],array('win','lose','draw')) ? $_POST['select'] : false;
if ($id && $select) {
$sql="UPDATE `test` SET `$select`=`$select`+1 WHERE `id`='$id';";
mysql_query($sql) or die(mysql_error());
}
}
// get data from database
$query = "SELECT * FROM test ORDER BY `id` DESC LIMIT 2";
$result = mysql_query($query) or die(mysql_error());
// output
?><h2>Seria A</h2><hr/><?php
while($row = mysql_fetch_assoc($result)){
?><p><?=$row['home']?> - <?=$row['away']?></p>
<form action="" method="post">
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="radio" name="select" value="win">1
<input type="radio" name="select" value="draw">X
<input type="radio" name="select" value="lose">2
<input type="submit" name="submit" value="Submit">
</form>
<p><?=$row['home']?> -> <?=$row['win']?></p>
<p>Barazim -> <?=$row['draw']?></p>
<p><?=$row['away']?> -> <?=$row['lose']?></p><?php
}
?>
Incidentally, how are you handling "home" vs "away" games?

Related

How to run SQL query on click using conditional PHP?

I am trying to create a room availability check page for a hostel and I am having an issue.
I have a database with a table named 'rooms' listing all type of rooms with these rows:
id [INT]
name (room type) [CHAR]
capacity (max capacity, not to be changed)[INT]
used (number of beds used, I want to change this dynamically!) [INT]
I created a code to generate the rooms list from the DB with PHP and I want the "+" and "-" buttons to either add or remove one unit in the used column for a specific room. How can I do this?
Here is my code:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
If you set the action of your form to whatever the name of your code is (e.g., "rooms.php"), then move
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
up to the top so it updates the table before you query the table to fill in the rest of the page, it should work. Right now, your php is updating the table after the SELECT query to populate your page, so it doesn't appear to be updating.
I think a better tack would be implementing AJAX so your form updates the Used field without reloading the page.
Alright so I figured out a way on my own in the end so I post it here for other people facing a similar issue to overcome it ;)
Here is the concerned part of the code in index.php:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
And the code of update.php:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}

How do I run multiple SQL Queries using "if(isset($_POST['Submit'])){"

Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}

editing data with a form

I am trying to edit data in my database but i cant get it to work.
i have tried breaking the script down to basics and troubleshoot each part.
The delete button works just fine but editting the data doesn't.
Where have i gone wrong?
my structure
database = domains table = domains_info row = domain
<?php include("header.php");
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM domains_info WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}}
$query = "select id, domain
from domains_info
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$domain = $row['domain'];?>
<form action='#' method='post' border='0' class="well form-horizontal">
<fieldset>
<label class="control-label" for="name">Domain</label>
<div class="controls">
<input id="name" type="text" name="name" value="<?php echo$domain; ?>">
<input type='hidden' name='id' value='<?php echo $id ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
</fieldset>
</form>
<?php echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>"; ?>
<script type='text/javascript'>
function delete_user( id ){
//prompt the user
var answer = confirm('Are you sure you want to delete <?php echo$name; ?>?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id of the record to be deleted
window.location = 'deletecontact.php?id=' + id;
}
}
</script>
the error im getting is this
Database Error: Unable to update record.
There is a extra ',' in your update query
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."',
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
with
$query = "update domains_info
set
domain = '".$mysqli->real_escape_string($_POST['domain'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";

update existing row in mysql using php coding

in my db i have 20+ columns. i added 19 columns throught input form and stored in db succesfully. i fetch few rows from db in my main page. in my main page 1 more column is there. that is status column, it is a combo box type. if i click status column it should show 4 values. i want to select one of the values and then when i click save button it must go to stored in db with that same ID. how to do that? i tried but its not updated in mysql db...
mainpage combo box coding:
echo "\t<td><form action=statusdb.php method=post>
<select name=update><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select>
<input name=\"update[".$a_row['slno']."]\"; type=submit id=id value=Save></form>
</td>\n";
status db coding:
if (isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$sql = mysql_query("UPDATE guestdetails SET status = '" . $_POST['update'] ."'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
help me how to do that?
In your IF should be $_POST, not $_GET
Also, need to add WHERE clause, like this:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guestdetails SET status = '$update' WHERE id='$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
Also, you used name update twice, once in <select> once in <input>, take that one from <input> out, make it hidden field with name id and value of your slno row:
echo "\t<td>
<form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option>
</select>
<input name='id' type='hidden' value='".$a_row['slno']."';>
<input type='submit'>Save</button>
</form>
</td>\n";
Try like below:
<form action="statusdb.php" method="post">
<?php
while($a_row = mysql_fetch_array($sql)) {
$sl_no = $a_row['slno'];
echo '<select name="update['.$sl_no.']"><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select> ';
echo '<input type="hidden" name="sl_no[]" value="'.$sl_no.'" />';
}
?>
<input name="update_rows" type="submit" value="Save">
</form>
<?php
if(isset($_POST['update_rows'])) {
$nums = $_POST['sl_no'];
$update = $_POST['update'];
foreach($nums as $sl) {
$sl_no = $sl;
$val = $update[$sl_no];
$sql_update = mysql_query("UPDATE guestdetails SET status = '$val' WHERE sl_no='$sl_no'");
}
}
?>
you are not submitting any id to status db.

Update echoed data using WHILE loop. Only updates one record

I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.

Categories