why this code dosen't update the data - php

I can't update the data on this code . it just return to the main page without any update . and i am sure about the connection data on connection file .
and all the column in the data bas is correct
so what is the problem please
<?
include "../include/config.php";
echo "<a href='del_update.php'>Delete</a>"
?>
<div class="articleall">
<?
$id = $_REQUEST['do'];
if($_REQUEST['do'] == 'remove'){
$gid= $_GET['id'] ;
$de = mysql_query("delete from article where id='$gid'");
if($de){
echo "Delete doen";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
}
#############################################
if($_REQUEST['do'] == 'update'){
$gid2 = $_GET['id'];
$sel = mysql_query("select * from article where id='$gid2'");
$row2 = mysql_fetch_assoc($sel);
$id2 =$row2['id'];
$name2= $row2['name'];
$auther2= $row2['auther'];
$text2 = $row2['text'];
####################################### post
$postid = $_POST['id'];
$postname = $_POST['name'];
$postauther = $_POST['auther'];
$posttext = $_POST['text'];
if($_POST['del_update']){
if($postname ==''){
echo "it is empty";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
else {
$update = mysql_query("update article set
name ='$postname',
auther='$postauther'
where id ='$postid'
");
if(isset($update)){
echo "update done ";
echo '<meta http-equiv="refresh" content="2; url=del_update.php"/>';
exit ;
}
}
}
?>
<form action="del_update.php?do=update" method="post" >
title : <input type="text" class="name" name="name" value="<?=$name2; ?>"></br>
auther : <input type="text" class="name" name="auther" value="<?=$auther2;?>"></br>
date : <input type="text" class="name" name="date" value=""></br>
<input type="hidden" class="name" name="id" value=""></br>
text : <textarea value="" id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">
<? echo $text2; ?>
</textarea>
<input type="submit" class="botton" value="update" name="go"><br>
</form>
<?
}
?>
<?
$query = mysql_query("select * from article order by id desc ");
while ($row = mysql_fetch_assoc($query)
){
$id = $row['id'];
$name = $row['name'];
echo "
<div class='shortarticle'>
<h3>$name ||
<a href='?do=remove&id=$id'>Delete</a>||
<a href='?do=update&id=$id'>Update</a>
</h3>
</div>
</div> ";
}
?>

Related

Populating checkboxes from database using PHP - only last option is getting checked

I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

How to remain stick to a php page?

I am passing the level of the question through query string to the page. Next, I am prompting user to give the answer from the option. Now, if the answer is correct, score is incremented. Now the issue is that if the answer is wrong, I am not getting any thing in browser.
<?php
session_start();
if ( isset($_POST['submit']))
{
$qid = $_POST['qid'];
$answer = $_POST['answer'];
// $range= $_POST['range'] ;
$dbc = mysqli_connect('localhost','root','1234','islamic')
or die('unable to connect');
$query = "select * from question where qid = '$qid' ";
$result = mysqli_query($dbc,$query);
$row = mysqli_fetch_array($result);
if ( $answer == $row['answer'])
{
// echo 'Congrats, Your answer is correct.'.$_COOKIE['username'];
#$score = ++$_COOKIE['score'];
setcookie('score',$score);
}
#$page = ++$_COOKIE['page'];
if ( #$page == 4)
{
echo 'score is '.$_COOKIE['score'];
setcookie('score',0);
setcookie('page',0);
echo 'Go to Home ';
exit();
}
setcookie('page',$page);
}
if ( isset($_GET['level']))
{
$_SESSION['level'] = $_GET['level'];
}
$level = $_SESSION['level'];
$dbc = mysqli_connect('localhost','root','1234','islamic')
or die('unable to connect');
// $query = "Select * from question";
// $result = mysqli_query($dbc,$query);
// $num_rows = mysqli_num_rows($result);
$range = rand(0,6);
$query = "select * from question where level = '$level' limit $range,1";
$result = mysqli_query($dbc,$query);
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['A']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['B']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['C']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['D']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
}
mysqli_close($dbc);
?>
You script doesn't display anything if the database query returns no results.
Get rid of the while and simply use $row = mysqli_fetch_array($result);

PHP Form update will not update

I have written an Edit part of my Form but somehow it will not Update the edited Fields. The Code does not give any Errors but it will not update?!
If possible could somebody take a look please?
<?php
include "connect.php";//database connection
if (isset($_GET["id"])) {
$id = intval($_GET["id"]);
if (isset($_POST["edited"]))
{
$update = "UPDATE traumprojekt SET";
$update .= sprintf("quantityProduct='%s', " , mysql_real_escape_string($_POST["quantityProduct"]));
$update .= sprintf("titleProduct='%s', " , mysql_real_escape_string($_POST["titleProduct"]));
$update .= sprintf("informationProduct='%s'", mysql_real_escape_string($_POST["informationProduct"]));
$update .= "WHERE id = '$id'";
mysql_query($update);
}
$sql = "SELECT * FROM `traumprojekt` WHERE id=$id";
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1)
{
$row = mysql_fetch_assoc($res);
?>
<form method="post" action="edit_form.php?id=<?php echo $row["id"] ?>">
ID: <?php echo $row["id"] ?><br />
Quantity: <input type="text" name="quantityProduct" value="<?php echo $row["quantityProduct"] ?>"><br />
Product Title: <input type="text" name="titleProduct" value="<?php echo $row["titleProduct"] ?>"><br />
Product Information: <input type="text" name="informationProduct" value="<?php echo $row["informationProduct"] ?>"><br />
<input type="submit" name="submit" value="Update"><br />
<input type="hidden" name="edited" value="1">
</form>
<?php
}
}
?>

Categories