【问题标题】:Missing variable data from SQLSQL 中缺少变量数据
【发布时间】:2023-04-07 13:50:01
【问题描述】:

我已从 SQL 中调用数据并按 id 选择 然后我想使用“mysqli_fetch_array”行[1]中的数据进行一些计算。

但不知何故,在第 14 行,$row[1] 无法获取进行计算的日期。

index.php

<?php
$con = mysqli_connect('localhost','root','','test2');
$query = mysqli_query($con,"SELECT * FROM count") or 
die(mysqli_error($con));


while( $row = mysqli_fetch_array($query))
  echo "$row[id]. $row[quantity] <a href='edit.php?edit=$row[id]'>Draw 
Patrs<br />";
?>

edit.php

<?php

if( isset($_GET['edit']) )
{
    $id = $_GET['edit'];
    $con = mysqli_connect('localhost','root','','test2');
    $query = mysqli_query($con,"SELECT * FROM count WHERE id='$id'");
    $row = mysqli_fetch_array($query);
}   

if( isset($_POST['drawquantity']) )
{
    $drawquantity = $_POST['drawquantity'];
    $newquantity = $row[1]-$drawquantity;
    $id      = $_POST['id'];
    $sql     = "UPDATE count SET quantity='$newquantity' WHERE id='$id'";
    $con = mysqli_connect('localhost','root','','test2');
    $res     = mysqli_query($con,$sql) 
                                or die("Could not update".mysql_error());
    echo "<meta http-equiv='refresh' content='0;url=index.php'>";

}

?>
<form action="edit.php" method="POST">
How mant you will take away: <input type="text" name="drawquantity" value="" 
placeholder="<?php echo $row[1]; ?>"><br />

<input type="hidden" name="id" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>

【问题讨论】:

  • 很可能当您提交edit.php 时,id 不再存在,因此所选行也不存在,我猜您应该在表单中保留相同的 url
  • 您的代码容易受到 SQL 注入的攻击。请学会使用prepared statements

标签: php sql


【解决方案1】:
<?php

if( isset($_GET['edit']) )
{
    $id = $_GET['edit'];
    $con = mysqli_connect('localhost','root','','test2');
    $query = mysqli_query($con,"SELECT * FROM count WHERE id='$id'");
    $row = mysqli_fetch_array($query);
}   

if( isset($_POST['drawquantity']) )
{
    $drawquantity = $_POST['drawquantity'];
    $newquantity = $row[1]-$drawquantity;
    $id      = $_POST['id'];
    $sql     = "UPDATE count SET quantity='$newquantity' WHERE id='$id'";
    $con = mysqli_connect('localhost','root','','test2');
    $res     = mysqli_query($con,$sql) 
                            or die("Could not update".mysql_error());
    echo "<meta http-equiv='refresh' content='0;url=index.php'>";

}

?>
<form action="edit.php?edit=<?=$_GET['edit']?>" method="POST">
How mant you will take away: <input type="text" name="drawquantity" value="" 
placeholder="<?php echo $row[1]; ?>"><br />

<input type="hidden" name="id" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>

改变在行动

【讨论】:

  • 感谢 Jinesh Suthar,您的代码正在运行,非常感谢
  • 也谢谢你。单击向上箭头,使其指示其有用。
猜你喜欢
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
相关资源
最近更新 更多