我有以下代码应该创建一个表并用两个用户填充它。 create table查询有效,但插入没有。任何帮助将不胜感激。
<?php
require_once 'login12.php';
$link = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$link) die ("Unable to connect to MySQL: " .mysqli_error());
mysqli_select_db($link, $db_database) or die("Unable to select database: " .mysqli_error());
$query = "CREATE TABLE `users` (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL)";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error());
$salt1 = 'G3tD0wnonIT!';
$salt2 = 'Y0uwant2';
$forename = 'Bill';
$surname = 'Smith';
$username = 'bsmith';
$password = 'mysecret';
$token = sha1("$salt2$password$salt1");
add_user($forename, $surname, $username, $token);
$forename = 'Pauline';
$surname = 'Jones';
$username = 'pjones';
$password = 'acrobat';
$token = sha1("$salt2$password$salt1");
add_user($forename, $surname, $username, $token);
function add_user($fn, $sn, $un, $pw) {
$query = "INSERT INTO `users` (`forename`, `surname`, `username`, `password`) VALUES ('$fn', '$sn', '$un', '$pw')";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error());
}
?>
答案 0 :(得分:1)
$link
超出了您的功能范围,因此无法访问它。您需要将它作为参数传递给您的函数。
add_user($link, $forename, $surname, $username, $token);
function add_user($link, $fn, $sn, $un, $pw) {
$query = "INSERT INTO `users` (`forename`, `surname`, `username`, `password`) VALUES ('$fn', '$sn', '$un', '$pw')";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error($link));
}
答案 1 :(得分:-1)
好吧,我之前的海报已经指出$ link不在你的功能范围内。我建议使用全局语句而不是将$ link作为参数添加到函数中,因为它更干净,你不必每次都传递它。
add_user($forename, $surname, $username, $token);
function add_user($fn, $sn, $un, $pw) {
global $link;
$query = "INSERT INTO `users` (`forename`, `surname`, `username`, `password`) VALUES ('$fn', '$sn', '$un', '$pw')";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error());
}