可以将INSERT,UPDATE,DELETE,SELECT查询放在同一个文件中

时间:2012-06-27 03:48:31

标签: php mysql

我有文件夹和页面/admin/add/index.php,/admin/edit/index.php& /admin/view/index.php这些都需要页面/admin/php.php,其中包含我的所有PHP代码,我无法打开流错误。我应该用<? ?>分隔它们,还是正在做我不可能做到的事情或最好的做法?

我的admin / php.php文件:

<?php
FOR ADD CONTACT PAGE

require ("../../dbandpassword.php");
$ID = $_POST['ID'];
$firstname = mysqli_real_escape_string($con,$_POST['firstname']);
$lastname = mysqli_real_escape_string($con,$_POST['lastname']);

$sql = "INSERT INTO table (firstname, lastname) VALUES ('$firstname', '$lastname')"; 

mysqli_query($con,$sql) or die ("Error: ".mysqli_error($con));

header("location: http://www.mydomain.com/admin/edit/?ID=".mysqli_insert_id($con));

exit;
}
FOR EDIT CONTACT PAGE

require ("../../dbandpassword.php");
$ID = $_POST['ID'];
$firstname = mysqli_real_escape_string($con,$_POST['firstname']);
$lastname = mysqli_real_escape_string($con,$_POST['lastname']);

$sql = "UPDATE table SET `firstname` = '$firstname', `lasttname` = '$lastname' WHERE `table`.`ID`  = '$ID' LIMIT 1";

mysqli_query($con,$sql) or die ("Error: ".mysqli_error($con));

FOR VIEW CONTACT PAGE

require ("../../dbandpassword.php");

$ID = $_GET['ID'];

$sql = "SELECT * FROM table WHERE ID='$ID' limit 1" or die ('Error: ' .mysqli_error());

$query = mysqli_query($con,$sql) or die ('Error: ' .mysqli_error($con));
$row = mysqli_fetch_array($query);

$space = (!empty($row['firstname']) && !empty($row['lastname'])) ? ' ' : '';        
$name = $row['firstname'].$space.$row['lastname'];       

mysqli_query($con,$sql) or die ("Error: ".mysqli_error($con));

FOR VIEW ALL CONTACTS PAGE

require ("../dbandpassword.php");

$ID=$_GET['ID'];

$query = "SELECT * FROM table WHERE firstname IN ('Bob','Joe') AND lastname = 'Smith' ORDER BY date DESC";

$result=mysqli_query($con,$query);
while ($row = mysqli_fetch_array($result)) {

$space = (!empty($row['firstname']) && !empty($row['lastname'])) ? ' ' : '';        
$name = $row['firstname'].$space.$row['lastname'];   

mysqli_query($con,$query) or die ("Error: ".mysqli_error($con));
}
?>

1 个答案:

答案 0 :(得分:5)

最好创建一个php文件,然后为每个动作创建单独的函数,如

function insert()
{

}

function delete()
{

}

function update()
{

}

function fetch()
{

}