简体   繁体   中英

PHP/MySQL: Two data input and save into one row in MySQL database

I new in PHP. FOr start, I want to create CRUD. Now I'm doing for 'create'. My database table contains, 'id', 'fullname', 'age', and 'email'.

But at my PHP page, user need to input, 'fname', 'lname', 'age' and 'email'. My question is, how I want to merge 'fname' and 'lname' and save it to table's row 'fullname'.

Below is my code:

<?php

include_once("config.php");
if(isset($_POST['Submit'])) {
$fname = $_POST['fname'];   
$lname = $_POST['lname'];
$age = $_POST['age'];
$email = $_POST['email'];


if(empty($fname) || empty($lname) || empty($age) || empty($email)) {

      if(empty($fname)) {
        echo "<font color='red'>Name field is empty.</font><br/>";
    }

      if(empty($lname)) {
        echo "<font color='red'>Name field is empty.</font><br/>";
    }

      if(empty($age)) {
        echo "<font color='red'>Age field is empty.</font><br/>";
    }

      if(empty($email)) {
        echo "<font color='red'>Email field is empty.</font><br/>";
    }

      echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else { 

      $sql = "INSERT INTO users(fullname, age, email) VALUES(:fullname, :age, :email)";
      $query = $conn->prepare($sql);

      $query->bindparam(':fullname', $fname,$lname);
      $query->bindparam(':age', $age);
      $query->bindparam(':email', $email);
      $query->execute();
      echo "<font color='green'>Data added successfully.";
      echo "<br/><a href='index.php'>View Result</a>";
}
 }
      ?>
      <html>
      <head>
     <title>Add Data</title>
      </head>

    <body>
   <a href="index.php">Home</a>
   <br/><br/>

   <form action="add.php" method="post" name="form1">
       <table width="25%" border="0">
          <tr> 
          <tr> 
            <td>Full Name</td>
            <td><input type="text" name="fname"></td>
          </tr>
            <td>Last Name</td>
            <td><input type="text" name="lname"></td>
          </tr>
          <tr> 
            <td>Age</td>
            <td><input type="text" name="age"></td>
          </tr>
          <tr> 
            <td>Email</td>
            <td><input type="text" name="email"></td>
          </tr>
          <tr> 
            <td></td>
            <td><input type="submit" name="Submit" value="Add"></td>
        </tr>
    </table>
</form>

连接它(我在名字和姓氏之间添加了一个空格) $query->bindparam(':fullname', $fname . ' ' . $lname);

You need to chose a parameter name then concatenate to that.

$query->bindparam(':fullname', $full);
$full = $fname . ' ' . $lname;

Additionally you'll need to change :fullnamename in the query to be :fullname otherwise you'll get an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM