2017-06-01 44 views
0

新的PHP和SQL,所以我创建了一个小的电影数据库,我有一些问题,我还没有能够解决。PHP控制小型数据库 - 添加和编辑(查询)

  1. 如何创建工作编辑功能?为了能够编辑数据库中的电影 。
  2. 如何将单选按钮的值转换为类别的SQL值?

希望这不是太多的代码。

<?php 
    require_once 'login.php'; 
    // Connection to databas 
    $conn = new mysqli($host, $username, $password, $dbname); 
    if ($conn->connect_error) die($conn->connect_error); 
    { 
    echo "Failed to connect to MySQL: (" . $conn->connect_error . ") " . $conn->connect_error; 
    } 
    // Delete movie from databas 
    if (isset($_POST['delete']) && isset($_POST['id'])) 
    { 
    $id = get_post($conn, 'id'); 
    $query = "DELETE FROM Movies WHERE id='$id'"; 
    $result = $conn->query($query); 
    if (!$result) echo "Delete failed: $query<br>" . 
     $conn->error . "<br><br>"; 
    } 
    // Edit movie 


    $title = filter_input(INPUT_POST, "title", FILTER_SANITIZE_SPECIAL_CHARS); 
    $director = filter_input(INPUT_POST, "director", FILTER_SANITIZE_SPECIAL_CHARS); 
    $year = filter_input(INPUT_POST, "year", FILTER_SANITIZE_NUMBER_INT); 
    $category = filter_input(INPUT_POST, "category", FILTER_SANITIZE_SPECIAL_CHARS); 
    $id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT); 

    if (isset($_POST['title']) && 
     isset($_POST['director']) && 
     isset($_POST['year']) && 
     isset($_POST['radio']) && 
     isset($_POST['id'])) 
    { 
    $title = get_post($conn, 'title'); 
    $director = get_post($conn, 'director'); 
    $year = get_post($conn, 'year'); 
    $category = get_post($conn, 'category'); 
    $id = get_post($conn, 'id'); 
    $query = "INSERT INTO Movies VALUES" . 
    "('$title', '$director', '$year', '$category', '$id')"; 
    $result = $conn->query($query); 
    if (!$result) echo "INSERT failed: $query<br>" . 
     $conn->error . "<br><br>"; 
    } 
    // Form for adding movies and radiobuttons for categories 
    echo <<<_END 
    <form action="sqltest.php" method="post"><pre> 
    Title: <input type="text" name="title"> 
    Director: <input type="text" name="director"> 
    Year: <input type="text" name="year"> 
    Category: 
    <input type="radio" name="query" value="1"> Action 
    <input type="radio" name="query" value="2"> Animated 
    <input type="radio" name="query" value="3"> Drama 
    <input type="radio" name="query" value="4"> Fantasy 
    <input type="radio" name="query" value="5"> Sci-Fi 
    <input type="radio" name="query" value="6"> Thriller 
    <input type="submit" value="Add Movie"> 
    </pre></form> 
_END; 

    // List all movies from databas 
    $query = "SELECT * FROM movies"; 

    $result = $conn->query($query); 
    if (!$result) die ("Database access failed: " . $conn->error); 
    $rows = $result->num_rows; 

    for ($j = 0 ; $j < $rows ; ++$j) 
    { 
    $result->data_seek($j); 
    $row = $result->fetch_array(MYSQLI_NUM); 

    echo <<<_END 
    <pre> 
    Title $row[0] 
    Director $row[1] 
    Year $row[2] 
    Category $row[3] 
    </pre> 
    <form action="sqltest.php" method="post"> 
    <input type="hidden" name="edit" value="yes"> 
    <input type="hidden" name="id" value="$row[4]"> 
    <input type="submit" value="Edit movie"></form> 
    <form action="sqltest.php" method="post"> 
    <input type="hidden" name="delete" value="yes"> 
    <input type="hidden" name="id" value="$row[4]"> 
    <input type="submit" value="Delete movie"></form> 
_END; 
    } 

    $result->close(); 
    $conn->close(); 

    function get_post($conn, $var) 
    { 
    return $conn->real_escape_string($_POST[$var]); 
    } 
?> 
+0

你能解释一下多一点的MySQL连接(本地主机,testdb的,root,密码)究竟是什么问题了吗?我可以看到你有编辑功能,但是你的错误是你试图插入,但你必须调用更新,因为数据已经在数据库中。而对于你的第二个问题,它也只是一个数字,你的意思是将其转换为SQL值? – Moein

回答

0

我重写了你的脚本(不使用所有表信息)。但你会看到,这很容易。但是,请使用PDO而不是MySQL或PHP的mysqli扩展。将来,这些扩展将从PHP中删除。 PDO是处理db事务的好方法。

我的脚本正在为插入,编辑和删除记录工作,但它应该只表示它的工作原理。

请更换数据库凭据

<?php 

$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=testdb', 'root', 'password', [ 
    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", 
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, 
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC 
]); 

$categories = [ 
    'None', 
    'Action', 
    'Animated', 
    'Drama' 
]; 

if (array_key_exists('action', $_GET)) { 
    switch ($_GET['action']) { 
     case 'add': 
      $query = 'INSERT INTO Movies SET title = :title, category = :category'; 
      $handle = $pdo->prepare($query); 
      $handle->bindValue(':title', $_POST['title'], PDO::PARAM_STR); 
      $handle->bindValue(':category', $_POST['category'], PDO::PARAM_INT); 
      $handle->execute(); 
      header('Location: ' . $_SERVER['PHP_SELF']); 
      die; 
     case 'edit': 
      $query = 'SELECT * FROM Movies WHERE id = :id'; 
      $handle = $pdo->prepare($query); 
      $handle->bindValue(':id', $_GET['id'], PDO::PARAM_INT); 
      $handle->execute(); 
      $record = $handle->fetch(); 

      $categoriesHtml = ''; 
      foreach ($categories as $catid => $cat) { 
       $selected = $catid == $record['category'] ? 'checked' : ''; 
       $categoriesHtml .= '<input type="radio" name="category" value="' . $catid . '" ' . $selected . ' /> ' . $cat . '<br>'; 
      } 

      echo <<<HTML 
<form method="post" action="?action=save"> 
    <input type="hidden" name="id" value="{$_GET['id']}" /> 
    <input name="title" value="{$record['title']}" /><br/> 
    {$categoriesHtml} 
    <input type="submit" name="save" value="Save" /> 
</form> 
HTML; 
      break; 
     case 'save': 
      $query = 'UPDATE Movies SET title = :title, category = :category WHERE id = :id'; 
      $handle = $pdo->prepare($query); 
      $handle->bindValue(':title', $_POST['title'], PDO::PARAM_STR); 
      $handle->bindValue(':category', $_POST['category'], PDO::PARAM_INT); 
      $handle->bindValue(':id', $_POST['id'], PDO::PARAM_STR); 
      $handle->execute(); 
      header('Location: ' . $_SERVER['PHP_SELF']); 
      die; 
     case 'delete': 
      $query = 'DELETE FROM Movies WHERE id = :id'; 
      $handle = $pdo->prepare($query); 
      $handle->bindValue(':id', $_GET['id'], PDO::PARAM_INT); 
      $handle->execute(); 
      header('Location: ' . $_SERVER['PHP_SELF']); 
      die; 
    } 
} 

if(isset($_GET['action'])){ 
    die; 
} 
echo '<ul>'; 
// List 
$handle = $pdo->query('SELECT * FROM Movies'); 
foreach ($handle->fetchAll() as $row) { 
    echo <<<HTML 
<li> 
    {$row['title']} - <a href="?action=edit&id={$row['id']}">edit</a> <a href="?action=delete&id={$row['id']}">delete</a> 
</li> 
HTML; 
} 
echo '</ul>'; 

$categoriesHtml = ''; 
foreach ($categories as $catid => $cat) { 
    $categoriesHtml .= '<input type="radio" name="category" value="' . $catid . '" /> ' . $cat . '<br>'; 
} 

echo <<<HTML 
<form method="post" action="?action=add"> 
    <input name="title" value="" /> 
    <br/> 
    {$categoriesHtml} 
    <input type="submit" name="save" value="Save" /> 
</form> 
HTML;