connect in php 5.6 +
This question already has an answer here:
For Myqli connection
$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");
For Query Please follow this answer How can I prevent SQL injection in PHP? it's really nice.
You could use this for query
$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
}
Most of mysql_ syntax you could use with mysqli_
As PHP is becoming a Object Oriented Scripting language, it will be better to make use of PDOs to make connections to Database and perform the operations, for this you have a give a little bit of more effort. Like making Entity Classes for each table's(each column as variable), this is the only hectic part but it will make the program more secure and more readable.
I am just giving the code for connecting to database and retrieving the dataset :
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();
}
Thanks and Regards.
链接地址: http://www.djcxy.com/p/26588.html下一篇: 连接在PHP 5.6 +