将选项选择到 mysql 数据库


Sens a option select to mysql database

我有一个选项选择,里面有 3 个选项(打开关闭和忙(。现在我想将我选择的选项发送到我的 Mysql 数据库。我得到了这个代码。

这是我的函数

function editStatus($pStatus, $id){
$id= (int) $id;
$query = mysql_query("UPDATE posts SET status = '$pStatus' WHERE id = '$id' ") or die (mysql_error());
}

在这里我调用我的函数

if (isset($_POST['submit'])) {
if(isset($_POST['postcats'])) {
    editStatus($_POST['postcats'] , $_POST['$id']);
    header('location: posts.php'); 
}else{
    echo "Please set a post name";
    include('addpost.php');
}
}else{
header('location: addpost.php');
}

这是我的表格

**                <tr>
                <TD><label for="postcats">Status</label></TD>
                <td><select name="postcats">
                       <option name="Open" value="Open">Open</option>
                       <option name="Busy" value="Busy">Busy</option>
                       <option name="Closed" value="Closed">Closed</option>
                    </select></td>
            </tr>
            <tr> 
                <td colspan="2"><input type="submit" name="submit" /></td><td><input type="hidden" name="id" value="<?php echo$_GET['id'];?>" /></td>
            </tr>**

我希望你们知道为什么它不会将其发送到我的数据库。

您正在调用editPost函数而不是editStatus

笔记

  • 添加error_reporting(E_ALL);ini_set('display_errors', 1);以捕获错误。

  • header("Location: ...");后添加die;exit;

  • 您容易受到sql注入的影响,因为没有逃脱$pStatus

  • mysql_* 函数已弃用。改用 mysqli 或 PDO。

我不确定为什么它不发布到数据库,您是否从 php 或 mysql 收到任何错误?另外,你不应该使用不推荐使用的mysql函数,而应该使用mysqli。并准备好语句以防止SQL注入。示例如下:

if (isset($_POST['submit'])) {
  if(isset($_POST['status'])) {
    editStatus($_POST['status'], $_POST['id']);
    function editStatus($status, $id) {
      // Get the mysql connection
      $mysqli = new mysqli('localhost', 'username', 'password', 'db');
      // Create a new prepared statement
      if($stmt = $mysqli->prepare("UPDATE posts SET status = ? WHERE id = ?")) {
        // Bind the parameters to replace the question marks on the query
        // In the correct order: si (String, Int)
        $stmt -> bind_param("si", $status, $id);
        // Execute the statement
        $stmt -> execute();
        // Close the statement
        $stmt -> close();
      }else {
        return $mysqli->error;
      }
      // Close the connection
      $mysqli -> close();
      return true;
    }
  }
}