很抱歉提出这个问题,我是初学者。但是在我写这篇文章之前,我已经搜索了类似的问题并且我已经尝试了但是它没有用,所以我决定在这里提问。
我这里有两张桌子:
CREATE TABLE users (
id_user char (4) PRIMARY KEY,
username varchar (20),
password varchar (200),
role set ('admin','operator','user)
);
CREATE TABLE info_user (
id_info char (4),
email varchar (200),
fullname varchar (200),
birthday date,
address varchar (200),
telephone varchar (200)
);
所以每个用户都有每个信息,属性id_info是id_user的外键。外键是真的吗?还是倒?以下是我的PHP代码:
<?php
include_once('config.php');
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$role = mysql_real_escape_string($_POST['role']);
$email = mysql_real_escape_string($_POST['email']);
$fullname = mysql_real_escape_string($_POST['fullname']);
$sex = mysql_real_escape_string($_POST['sex']);
$birthday = mysql_real_escape_string($_POST['birthday']);
$adress = mysql_real_escape_string($_POST['adress']);
$telephone = mysql_real_escape_string($_POST['telephone']);
$confirm_pass = ($_POST['confirm_password']);
if ($confirm_pass != $password) {
echo" <script language='JavaScript'> alert ('Password didn't match!');</script>";
echo '<script language="JavaScript"> window.location.href ="register.php" </script>';
} else {
$dup = mysql_query("SELECT username FROM users WHERE username='".$_POST['username']."'");
if(mysql_num_rows($dup) >0){
echo"<script language='JavaScript'> alert ('Username is already exist');</script>";
echo '<script language="JavaScript"> window.location.href ="register.php" </script>';
} else {
// simpan data ke database
$query1 = mysql_query("insert into users values('', '$username', '".md5($_POST['password'])."', '$role'");
$query2 = mysql_query("insert into info_user values ('', '$email', '$fullname', '$sex','$birthday','$adress','$telephone')");
if ($query1 && $query2) {
// if success to save data
echo" <script language='JavaScript'> alert ('Your registration is successfull');</script>";
echo '<script language="JavaScript"> window.location.href ="halaman_admin.php" </script>';
} else {
// if failed to save data
echo" <script language= 'JavaScript'> alert ('There's error occured, please try again!'); </script>";
echo '<script language="JavaScript"> window.location.href ="register.php" </script>';
}}
}
?>
我试过这段代码,但它没有用。如何使其工作?那些表是相关的。提前谢谢你的帮助,我真的需要这个。
答案 0 :(得分:0)
由于您需要新创建的user
行中的密钥才能正确创建info_user
行,因此您需要执行此操作。
// simpan data ke database
$query1 = mysql_query("insert into users values('',
'$username',
'".md5($_POST['password'])."',
'$role'");
if ( $query1 ) {
$new_id_user = mysql_insert_id(); // get id_user of newly created user row
$query2 = mysql_query("insert into info_user values ($new_id_user,
'$email',
'$fullname',
'$sex',
'$birthday',
'$adress',
'$telephone')");
if ( ! $query2 ) {
// insert of info_user failed, code appropriatly
}
} else {
// insert of new User failed, code appropriatly
}