为每个查询(sample1)创建单独的数据库连接是否更好/安全?或者我应该为两个查询创建一个数据库连接(sample2)?
我有2个查询要发送到数据库。
我主要对一种方法的安全性和资源成本感兴趣。
注意:下面的示例代码是用户注册码的简化版本。
样本1。
<?php
$NEW_EMAIL="sample@gmail.com";
$prep_sel = 'SELECT email FROM users WHERE email=?';
$link1 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link1, $prep_sel)) {
mysqli_stmt_bind_param($link1, 's', $e);
mysqli_stmt_execute($link1);
mysqli_stmt_store_result($link1);
}
// If record does not exist, then insert it.
if (mysqli_stmt_num_rows($link1) == 0) { // Available.
$prep_ins= 'INSERT INTO users (email) VALUES (?)';
$link2 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link2, $prep_ins)) {
mysqli_stmt_bind_param($link2, 'sssss', $NEW_EMAIL);
mysqli_stmt_execute($link2);
}
}
?>
样本2。
<?php
$NEW_EMAIL="sample@gmail.com";
$prep_sel = 'SELECT email FROM users WHERE email=?';
$link1 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link1, $prep_sel)) {
mysqli_stmt_bind_param($link1, 's', $e);
mysqli_stmt_execute($link1);
mysqli_stmt_store_result($link1);
}
// If record does not exist, then insert it.
if (mysqli_stmt_num_rows($link1) == 0) { // Available.
$prep_ins= 'INSERT INTO users (email) VALUES (?)';
if (mysqli_stmt_prepare($link1, $prep_ins)) {
mysqli_stmt_bind_param($link1, 'sssss', $NEW_EMAIL);
mysqli_stmt_execute($link1);
}
}
?>
答案 0 :(得分:2)
是否有样本3选项?如果您将数据库中的email
列更改为UNIQUE
,则表示不允许重复的电子邮件。见下表样本:
CREATE TABLE users
(
id int auto_increment primary key,
email varchar(20) unique
);
如果您尝试注册已使用该给定电子邮件的新帐户,您将收到错误1062(即重复输入错误)。
因此,如果您的电子邮件列为SELECT
,则可以简单地运行INSERT
查询,而不是同时运行INSERT
和UNIQUE
查询。 / p>
<?php
// Your database info
$db_host = 'xxxx';
$db_user = 'xxxx';
$db_pass = 'xxxx';
$db_name = 'xxxx';
// hardcoded email for testing purposes
$test_email ="sample@gmail.com";
// SQL query
$sql = 'INSERT INTO users (email) VALUES (?)';
// connect to database
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
// Prepare the query to make sure it is good to go
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
// bind and test if the parameters are valid
if (!$result->bind_param('s', $test_email))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
// execute and see if it executed as expected.
if (!$result->execute())
{
if ($result->errno === 1062)
{
die("Email already in use...");
}
else
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
}
else
{
echo "account created!!";
}
In regards whether its better to have a single connection or multiple connections, this is a very good reading但作为简历,您可以将自己引用到In PHP/MySQL should I open multiple database connections or share 1?