SoFunction
Updated on 2025-04-13

Learn to write a simple address book with a database in 30 minutes. Page 2/3


File code:
Copy the codeThe code is as follows:
<form  name="form1" method="post" action=""> 
<p>Name: <input name="name" type="text" //</p>
  <p> 
Gender: <input type="radio" name="sex" value="0" /Ms.
<input type="radio" name="sex" value="1" // Mr.
  </p> 
<p>Mobile phone: <input name="mobi"  type="text"  //</p>
<p>Email: <input name="email" type="text"   //</p>
<p>Address: <input name="addr"  type="text"  //</p>
  <p> 
<input type="submit" name="Submit" value="Add" />
<input type="reset" name="Submit2" value="rewrite" />
  </p> 
</form> 
Note: Because there is only HTML code, it is OK if you want to save it in html format. Don’t be confused by those messy <p></p>s. The keyword we want to look at is form and input. form mainly looks at method and action. method is a method, including post and get, etc. You can learn about this yourself; action is an action, which means transmitting a worthy target page. To be more common, it is the page you will be able to hit by clicking the button. So, what you need to pay attention to when input is name and id, and you need to define some easy-to-remember names. For the sake of memory convenience, I defined the form name and the database field name as the same. This is not necessary, but it is still necessary. The last thing to note is sex. Don’t think wrongly, I’m talking about gender. Be sure to note that its name is the same, but the value is different. We have already said before, use 0 to represent women and 1 to represent men. This form is recommended to use some tools, such as DW, etc., and it can be done in a few seconds. If you write by hand, you need to have a certain html language foundation. If you use utf8, you must remember to use tools to save all web pages as utf8.
File code: (incomplete) 
Copy the codeThe code is as follows:
<?php 
//Set form variables
$name  = $_POST[’name’]; 
$sex     = $_POST[’sex’]; 
$mobi   = $_POST[’mobi’]; 
$email   = $_POST[’email’]; 
$addr    = $_POST[’addr’]; 
//Test whether to pass the value
echo $name  . ’<br>’; 
echo $sex     . ’<br>’; 
echo $mobi   . ’<br>’; 
echo $email   . ’<br>’; 
echo $addr    . ’<br>’; 
?>

Note: This is an incomplete code. Let's first write some simple scripts to test whether the value is successfully passed to the page. "Setting form variables" is not necessary, but it is also necessary to avoid unexpected situations, haha. The variable you are seeing now, such as $name, is the name in the previous one. For example: <input name="mobi"  type="text"  /> (page), the name="mobi" in it is $mobi  (page) here, right? Then run the page, fill in some information casually, and then press "Add". If you press "Add", go to the page and display the content you filled in correctly, it means that the value transmission is successful, and we can continue to do it offline. Tip: echo is the printout, similar to $name starting with $ is variable, <br>Break line. echo is a language structure, not a function, remember this.
OK, the value is successfully passed, so what we need to do is write the value into the database. Before improving, we first write a file and call it for some operations in the database. So let's take a look at this simple code:
File code:
Copy the codeThe code is as follows:
<?php 
//Set database variables
$db_host   = ’localhost’;  //The database host name is generally localhost
$db_user  = ’root’;         //Database user account, depending on personal circumstances
$db_passw = ’123456’;   //Database user password, depending on personal circumstances
$db_name = ’list’;          //The specific name of the database shall be subject to the database created just now.
//Connect the database
$conn = mysql_connect($db_host,$db_user,$db_passw) or die (’Database connection failed!’);
//Set character sets, such as utf8 and gbk, depending on the character set of the database.
mysql_query("set names ’utf8’"); 
//Select database
mysql_select_db($db_name,$conn) or die(’Database selection failed!’);
//Execute SQL statements (query)
$result = mysql_query($sql) or die(’Database query failed!’);
?> 
Note: This code itself has no effect, because it needs to be used frequently, so it is just to reduce the workload and do not have to repeat it, so it is placed in a file so that it can be called at any time. There is no need to explain more here. You just need to change the "Set Database Variables" and "Set Character Set" parts according to your personal situation. Don't try to run this script separately, there will definitely be an error, because we haven't started setting $sql yet.
OK, the basic operations of the database are done. Let's start writing the full version, haha.
File code: (full version)
Copy the codeThe code is as follows:
<?php 
//Set form variables
$name  = $_POST[’name’]; 
$sex     = $_POST[’sex’]; 
$mobi   = $_POST[’mobi’]; 
$email   = $_POST[’email’]; 
$addr    = $_POST[’addr’]; 
// SQL statements that need to be executed (here is the insert data function)
$sql = "INSERT INTO `addr_list` 
                ( `id` , `name` , `sex` , `mobi` , `email` , `addr` )  
                VALUES 
                (NULL , ’$name’, ’$sex’, ’$mobi’, ’$email’, ’$addr’)"; 
//Calling files for database operations
require(’’); 
// Prompt the operation success information, note: $result exists in the file and is called.
if($result) 

echo ’Congratulations, the operation was successful! <p>’;

?> 
[<a href="">View address book</a>] [<a href="">Continue to add</a>]
Note: The full version I finally saw is simple enough, right? hehe. What you need to pay attention to here is the SQL statement in $sql. If you don’t know how to deduct SQL statements, you can use phpMyadmin to deduct them. Please google them yourself and write them separately if you have time. It is better to learn SQL grammar. Let’s look at $sql. I id corresponds to NULL. As mentioned earlier, you don’t have to worry about it after the id is established, so you can leave a blank value. Next, the name field of the database corresponds to the $name variable, and so on. Write out the statement you need to execute, and then call to execute. It's that simple. In order to make the interface more user-friendly, we should add some operation prompts and related links. In this way, ours is done, haha, super simple. However, it is better to pursue simplicity when used for learning, haha.
OK, let's do it now and display the page. Already completed nearly half of the award, and you will be done if you persist.
File code:
Copy the codeThe code is as follows:
[<a href="">Continue to add</a>]
<?php 
//This is PHP code
$sql = "SELECT * FROM `addr_list`";// SQL statements that need to be executed (here is the browsing data function)
require(’’);
?> 
<!--- Here HTML code, create a table--->
        <table width="100%" border="1"> 
         <tr> 
<th bgcolor="#CCCCCC" scope="col">name</th>
<th bgcolor="#CCCCCC" scope="col">Gender</th>
<th bgcolor="#CCCCCC" scope="col">Mobile</th>
<th bgcolor="#CCCCCC" scope="col">email</th>
<th bgcolor="#CCCCCC" scope="col">Address</th>
         </tr> 
<?php 
//This is PHP code
while($row = mysql_fetch_row($result))//Loop starts

//Judge gender
        if($row[2]==0) 
        { 
$sex= ’Ms.’;
        } 
        else 
        { 
$sex= ’Mr.’;
        } 
?> 
<!---The looped HTML table contains PHP code--->
            <tr> 
              <td><?php echo $row[1]; ?></td> 
              <td><?php echo $sex;      ?></td> 
              <td><?php echo $row[3]; ?></td> 
              <td><?php echo $row[4]; ?></td> 
                <td><?php echo $row[5]; ?></td> 
            </tr> 
<?php 

?> 
</table>

Note: This code is extremely nonsense, because we cannot talk about template engines such as Smarty and PHPlib, so we can only throw it into the same file with HTML in PHP. However, we must not do this when we are developing, otherwise I will become a sinner forever. As the situation is forced, everyone will just let it go. It's not difficult to understand. Grasp one principle. <?php The one in it is PHP code?>, on the contrary, the one outside is HTML code. Let’s focus on while($row = mysql_fetch_row($result)). Here mysql_fetch_row($result) saves the result set we execute SQL statements to obtain as an array. Of course, you don't need to rush to understand what an array is. You just need to know that it helps our fields line up. Remember to queue up from 0: 0->id;  1->name;  2->sex;  3->mobi;  4->email;  5->addr   This is clear at a glance. When we need to call it, we use $row[X] to call it. X is the queue number. For example, call name, which is $row[1]. Because we do not require id to be displayed, there is no $row[0] in the above code, so why is there more $sex? Because we cannot use numbers to display gender, we added a conditional sentence: If $row[2] is equal to 0, then "Ms.", otherwise "Mr.". Of course you can change the gender title at will, such as 0 shows Eve and 1 shows Adam, haha.
OK, then let's get here first. There are two parts left: modify and delete, we will get them next time. It looks fast, but it is not that easy to write. My hands are almost dislocated, haha.
Previous page123Next pageRead the full text