连接在PHP 5.6 +
这个问题在这里已经有了答案:
对于Myqli连接
$mysql_hostname = "localhost";
$mysql_user = "dbuser";
$mysql_password = "dbpass";
$mysql_database = "dbname";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password,$mysql_database) or die("Could not connect database");
对于查询请按照这个答案如何防止PHP中的SQL注入? 这太好了。
你可以用它来查询
$sql=sprintf("SELECT qu_text FROM `quotes` WHERE qu_text LIKE '%s%%'"),mysqli_real_escape_string($bd,$q));
$fetch= mysqli_query($bd,$sql) or die(mysql_error());
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
//Your Result
}
你可以使用mysqli_的大部分mysql_语法
由于PHP正在成为面向对象的脚本语言,因此利用PDO与数据库建立连接并执行操作将会更好,因此您可以付出更多努力。 就像为每个表格(每列作为变量)创建实体类一样,这是唯一的忙乱部分,但它会使程序更安全,更具可读性。
我只是给连接到数据库和检索数据集的代码:
1. DBConfig.php
$dsn = 'mysql:dbname=<database-name>;host=<host-name>';
$user = '<user-name>';
$password = '<password>';
try
{
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
2. Search.php
require_once 'DBConfig.php'; //If DBConnection is not made in same file
require_once '<name-of-entity-class>.php';
$q = (isset($_POST['q']) && !empty($_POST['q'])) ? $_POST['q'] : NULL;
try
{
$query = "SELECT qu_text FROM quotes WHERE qu_text LIKE :q";
$stmt = $conn->prepare($query);
$stmt->bindValue(':q', $q, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch())
{
$dataset[] = new <name-of-entity-class>($row);
}
if(!empty($dataset))
{
foreach ($dataset as $data)
{
echo '<p>';
echo $data->get<var-name>;
echo '</p>';
}
}
else
echo 'empty database';
}
catch (Exception $ex)
{
echo 'Some error occured: ' . $e->getMessage();
}
感谢致敬。
链接地址: http://www.djcxy.com/p/26587.html上一篇: connect in php 5.6 +
下一篇: deprecated