我为这个类创建了这个网页,我需要将两个单独的HTML表单输入连接起来,并将它们插入到MySQL数据库中。具体来说,我要求用户在单独的HTML表单输入中输入他们的名字和姓氏,我必须将这两个输入连接成一个全名,中间有一个空格(或者" Bob"和&#34 ; Ross"连接将是" BobRoss"而不是" Bob Ross")。这样做时我不知道从哪里开始。此外,我需要在将数据库插入数据库之前检查数据库中是否已存在全名,但我已经使用名字和姓氏进行了操作,因此不应该这样做硬。
以下是包含表单输入的HTML页面:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
这是PHP页面,它将数据输入数据库。目前我输入用户的名字,姓氏和年龄,但我需要连接名字和姓氏,并确保它不在数据库中,然后将其插入到数据库,我还没有做到。目前我确保名字是唯一的,我确保姓氏是唯一的,但我不在乎年龄是否独特。
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
答案 0 :(得分:2)
首先,您不应该使用
mysql
函数作为此扩展程序 从PHP 5.5.0开始已弃用,将来会被删除。 我建议使用新的改进的PDO库和PDO准备语句,请参阅here。
至于连接,你可以这样做:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
这会将名称与两者之间的空格连接起来。
然后,您可以在查询中使用$concatenated_name
。
但是我仍强烈建议您将PDO用于所有功能。
答案 1 :(得分:-1)
$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);