如何将php连接到mysql数据库?
问题描述:
我正在为网站制作搜索引擎,但以前从未使用过PHP,并且一直在尝试使用以下代码将网页连接到mysql数据库:
I'm making a search engine for a website and I've never used PHP before and I have been trying to connect my webpage to a mysql database using this code:
$dbhost = 'hosthere';
$dbuser = 'usernamehere';
$dbpass = 'passwordhere';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
但是我也读过不要使用mysql_ *函数,因为它们很快将不再可用,但是我在其他任何地方都没有看到过.
but I also read not to use the mysql_* functions as they will soon not be usable any longer but I haven't seen that anywhere else.
我要连接的旧代码是:
define('DB_SERVER', 'serverhere');
define('DB_SERVER_USERNAME', 'usernamehere');
define('DB_SERVER_PASSWORD', 'passwordhere');
define('DB_DATABASE', 'databasehere');
define('STORE_DB_TRANSACTIONS', 0);
define('DEBUG', 0);
db_connect() or die('Unable to connect to database server!');
我应该坚持还是使用顶部的代码?
Should I just stick with that or use the code at the top?
答
在这里,您可以使用PDO.
here you go, using PDO.
define("SQLHOST", "127.0.0.1");
define("SQLUSER", "login");
define("SQLPASS", "password");
define("SQLSGBD", "database");
$conn = new PDO('mysql:host=' . SQLHOST . ';dbname=' . SQLSGBD . ';charset=UTF8', SQLUSER, SQLPASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql1 = 'SELECT * FROM table where field1=?';
$stmt1 = $conn->prepare($sql1);
$field1="test";
$stmt1->bindParam(1, $field1, PDO::PARAM_STR);
try {
$stmt1->execute();
$result = $stmt1->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
if ($showError === true) {
var_dump("error query 1:" . __LINE__ . "-------" . __FUNCTION__ . "-------" . $e->getMessage());
exit;
}
}