私はあなたがPHP frameworkを学習に投資したいと思うでしょうので、残念ながら、あなたがここで起こっていることは"spaghetti code"症候群の始まりだと思います。あなたは$_GET
でbookid
を設定し、他のもののうち、あなたがsql injectionの問題を持って、この特定のスニペットについて
など、スクリプトが取得-行く、より-容易に維持からきれいになり、セキュリティ上の問題の少ないチャンスを持っていますと$_POST
がありますが、どちらが最適なのかを判断するのは難しいですが、<html>
タグの上にhtmlがありますが、主な問題はif
というスコープで定義されている変数ですが、if
スコープの外でも参照されていますif
の条件が満たされていない場合にエラーが発生します(詳細はSee this example)。
スコープの問題を修正する以外にもいくつかの提案:
- 結合パラメータで
PDO
またはmysqli_
を使用してください。私の例では、あなたの最終的なレイアウト(それは私が下のそれを持っているように、より複雑に見えますが、それはすべて1つのページに貼り付けていますだけの理由。各ページは別々でなければなりません)での使いやすさと読みやすさの両方のためにPDO
- 使用functionsまたはclass/methodを使用しています。この
$query
、$query1
、$query2
などはすべて混乱します。私は関数を使用しましたが、クラスは内部ですべてのメソッドにbookid
を渡す方が良いでしょう。
- 書籍IDのキー名を標準化してください(
book_id
またはbookid
)。私の例ではbookid
を使用しています。
これにはいくつかの瑕疵がありますが、これまでに述べたように、これはクラス(実際にはいくつかのクラス)として実装すると便利ですが、あなたのスクリプトをきれいにするのを手伝ってください。
重要:私はこれをテストしていませんが(構文エラーはありません)、何が起こっているのか、お使いのバージョンをこれと並列化することによって何が起こっているのかを知ることができます。あなたがそれを理解していない場合は、最初にそれを読んで、盲目的にコピー&ペーストしないでください。彼らが言うように、あなた自身の責任で使用してください。
/functions/getBooks.php
# Create a general function to fetch all books.
function getBooks($con)
{
$result = array();
$query = $con->prepare("SELECT * FROM books");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/functions/getBookById.php
# Create a function to fetch a specific book by id
function getBookById($id,$con)
{
$query = $con->prepare("SELECT * FROM books WHERE bookid = :id");
$query->execute(array(":id"=>$id));
$row = $query->fetch(PDO::FETCH_ASSOC);
return (!empty($row))? $row : array();
}
/機能/ getBook。PHP
# This should fetch from a global request, that way you can tell if
# a book is currently being accessed
function getBook($con)
{
autoload(array('getBookById','getId'));
$id = getId('req');
if(empty($id))
return false;
return getBookById($id,$con);
}
/functions/updateBookById.php
# Create an update function that can be accessed at anytime. Use binding
# so you don't need to mess with any sort of escaping
function updateBookById($id,$values,$con)
{
foreach($values as $keys => $vals) {
$bKey = ":{$keys}";
$bind[$bKey] = $vals;
$sql[] = '`'.$key.'` = '.$bKey;
}
$bind[":id"] = $id;
$query = $con->prepare("UPDATE books SET ".implode(', ',$sql)." WHERE bookid = :id");
$query->execute($bind);
}
/functions/updateBookTitle.php
# This is is just a specific function to focus on title. Not sure you need
# it since the update book by id function would do the same thing
function updateBookTitle($id,$title,$con)
{
$bind[":id"] = $id;
$bind[":title"] = $title;
$query = $con->prepare("UPDATE books SET title = :title WHERE bookid = :id");
$query->execute($bind);
}
/functions/getId.php
# This will fetch the id value from a global
function getId($type = false)
{
switch($type) {
case('post'):
return (isset($_POST['bookid']))? $_POST['bookid'] : false;
case('req'):
return (isset($_REQUEST['bookid']))? $_REQUEST['bookid'] : false;
default:
return (isset($_GET['bookid']))? $_GET['bookid'] : false;
}
}
/functions/bookObserver.php
# This will sit and just wait for the right globals activate it
function bookObserver($con,&$curr)
{
autoload('getId');
if(getId('req')) {
autoload('getBookById');
$books = getBookById(getId('req'),$con);
if(!empty($books))
$curr = $books;
if(isset($_POST['Update'])) {
$values = array(
'title' => $_POST['title'],
'author' => $_POST['author'],
'publisher' => $_POST['publisher'],
'numcopies' => $_POST['numcopies'],
'shelfno' => $_POST['shelfno'],
'status' => $_POST['status']
);
autoload('updateBookById');
updateBookById(getId('req'),$values,$con);
}
}
}
/functions/bookListObserver.php
# This sits and waits for the update to write the table to the page
function bookListObserver($current,$con)
{
if(isset($_POST['Update'])) {
autoload('bookList');
echo bookList(((!empty($current['status']))? $current['status'] : false),$con);
}
}
/functions/getValue.php
# This will just check if a value is set. Saves on scripting
function getValue($array,$key,$def = false)
{
return (!empty($array[$key]))? $array[$key] : $def;
}
/functions/bookList.php
# Displays your book list. Currently you are only showing the last book,
# which doesn't appear correct. No point in getting all books but only showing
# the last one
function bookList($selected = false,$con)
{
autoload('getBooks');
$books = getBooks($con);
ob_start();
?>
<table>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>numcopies</th>
<th>shelfno</th>
<th>status</th>
<th>Action</th>
</tr>
<?php foreach($books as $row) { ?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['author'] ?></td>
<td><?php echo $row['publisher'] ?></td>
<td><?php echo $row['numcopies'] ?></td>
<td><?php echo $row['shelfno'] ?></td>
<td><?php echo $row['status'] ?></td>
</tr>
<?php } ?>
</table>
<?php
if($selected == "Available")
echo "selected";
elseif($selected == "Unavailable")
echo "selected";
$data = ob_get_contents();
ob_end_clean();
return $data;
}
/functions/connect.php
# This is your mysql connection, it requires attention to build out
# It's not as useful as it could be, so you will want to research it
function connect()
{
return new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
}
/functions/autoload.php
# This is just a handy function to autoload functions when you want
# to use them. If you used classes, you would make an spl_autoload_register()
# function or install something like Composer to autoload
function autoload($name,$run = false)
{
if(is_array($name)) {
foreach($name as $func) {
autoload($func);
}
return;
}
if(!function_exists($name)) {
if(is_file($file = FUNCTIONS.DS.$name.'.php'))
include_once($file);
}
if($run) {
if(function_exists($name))
return $name();
}
}
/confi g.php
# Make sure errors are on in testing
ini_set('display_errors',1);
error_reporting(E_ALL);
# Creating commonly-used defines will help your scripts be
# more reliable and consistent
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('DB_HOST','localhost');
define('DB_NAME','library book');
define('DB_USER','root');
define('DB_PASS','');
# Start session by default
session_start();
require_once(FUNCTIONS.DS.'autoload.php');
# Autoload the connect function and assign it
$con = autoload('connect',true);
/index.php
<?php
# Add config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Include all our starting page functions
autoload(array('bookObserver','bookListObserver','getBook', 'getValue'));
# Set default array for current selection
$current = array();
# Start observer, pass connection
bookObserver($con,$current);
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<?php
# This writes the table if update is set
# You should not put this html above the <html> tag
bookListObserver($current,$con);
# This gets the book from the page request
$book = getBook($con);
?>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo getValue($book,'title') ?>"><br/>
EnterAuthor:<input type="text" name="author" value="<?php echo getValue($book,'author') ?>" ><br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo getValue($book,'publisher') ?>"><br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo getValue($book,'numcopies') ?>"><br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo getValue($book,'shelfno') ?>"><br/>
<input type="hidden" name="bookid" value="<?php echo getValue($book,'bookid') ?>" />
<select>
<option value="available" <?php if(isset($current['status']) && $current['status'] == "Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if (isset($current['status']) && $current['status'] == "Unavailable") echo "selected";?>>Unavailable</option>
</select><br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>
使用 'mysqli'または' pdo'拡張。 mysql拡張は非推奨です。 –
サイドノート、これをしないでください。 '$ bookid = $ _GET ['book_id']; $ str = "book *からbookid = $ bookid"を選択します。これは、データベースを一掃する簡単な方法です。 – Rasclatt
あなたは郵便で本IDを送るべきです。あなたがページを提出するときにページを更新し、$ _GETではない$ _POST値が得られるので、$ _GET条件に入りません。 –