如何更新表中的值

时间:2016-03-07 16:07:11

标签: php sql

我无法使用此代码更新表格中的值,如果更新成功,页面应重定向('位置:ui.php'),如何实现?

<?php
ob_start();
include('dbconnect.php');

$code=$_GET['stallcode'];

if(isset($_POST['submit']))
{
    $pcost = $_POST['pcost'];
    $tcost = $_POST['tcost'];
    $cash = $_POST['cash'];
    $change = $_POST['change'];
    if (($cash == '0')) 
    {
        $pstatus="0";
    }
    else
    {
        $pstatus="1";
    }

    $updated=mysql_query("UPDATE tbl_stallowner SET 
            paymentstatus='$pstatus', penaltycost='$pcost',        totalcost='$tcost', cash='$cash', change='$change' 
            WHERE stallcode='$code'")or die();
    if($updated)
    {
        $msg="Successfully Updated!!";
        header('Location:ui.php');
    }
}  //update ends here

ob_end_flush();
?>

2 个答案:

答案 0 :(得分:0)

当您通过选中if($updated)时重定向用户,这不起作用,您应该使用mysql_num_rows检查受影响的行数。

还要记住在exit;之后header()停止执行。

$num_rows = mysql_num_rows($updated);
if($num_rows > 0)
{
$msg="Successfully Updated!!";
header('Location:ui.php');
exit;
}

提示:您不应该使用MySQL,因为它已被弃用,请改用MySQLi

答案 1 :(得分:0)

你想使用mysqli,而不是它的前身mysql。 Mysql易受攻击并且容易受到攻击,这就是你应该在每个文件中编写的内容:

  

dbconnect.php

    <?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
  

updatestallowner.php(或任何你命名的)

<?php
ob_start();
require('dbconnect.php');
$code = mysqli_real_escape_string($conn, $_GET['stallcode']);
if(isset($_POST['submit'])){
    $pcost = mysqli_real_escape_string($conn, $_POST['pcost']);
    $tcost = mysqli_real_escape_string($conn, $_POST['tcost']);
    $cash = mysqli_real_escape_string($conn, $_POST['cash']);
    $change = mysqli_real_escape_string($conn, $_POST['change']);
    if ($cash == '0') {
        $pstatus="0";
    } else{
        $pstatus="1";
    }

    $sql = "UPDATE tbl_stallowner SET paymentstatus='$pstatus', penaltycost='$pcost', totalcost='$tcost', cash='$cash', change='$change' WHERE stallcode='$code';";
    $result = mysqli_query($conn, $sql);
    if($result) {
        $msg="Successfully Updated!!";
        header('Location: ui.php');
        exit;
    } else {
        die("Error updating!");
    }
}

?>
祝你好运!