[英]How to connect php to mysql database?
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: 我正在为网站制作搜索引擎,但以前从未使用过PHP,并且一直在尝试使用以下代码将网页连接到mysql数据库:
$dbhost = 'hosthere';
$dbuser = 'usernamehere';
$dbpass = 'passwordhere';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
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. 但是我也读过不要使用mysql_ *函数,因为它们很快将不再可用,但是我在其他任何地方都没有看到。
My old code to connect is: 我要连接的旧代码是:
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? 我应该坚持使用还是使用顶部的代码?
here you go, using PDO. 在这里,您可以使用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;
}
}
This is explained at http://php.net/manual/en/function.mysql-connect.php 这在http://php.net/manual/en/function.mysql-connect.php中进行了解释
You should use one of the extensions: MySQLi or PDO_MySQL 您应该使用以下扩展名之一:MySQLi或PDO_MySQL
With MySQLi you basically add an i to the new version of your code (do not use the old code) further information can be found here: http://php.net/manual/en/function.mysqli-connect.php . 使用MySQLi,您基本上可以在代码的新版本中添加i(不要使用旧代码),可以在以下位置找到更多信息: http : //php.net/manual/en/function.mysqli-connect.php 。 Otherwise please look at http://php.net/manual/en/pdo.construct.php
否则,请查看http://php.net/manual/en/pdo.construct.php
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.