Use php to read and write mysql database and display it on the web page

Due to work reasons, it is necessary to understand the process of reading and writing the database under the bs mode, and sort out the test process.

I used phpstudy to build the database, the mysql database has been built, and the name is version 2018, as shown below:

Since I installed the apache service in the early stage, there are some conflicts. Sometimes, it may be necessary to manually start the mysql service to connect normally. The verification method is from the mysql manager -> phpmyadmin to open the following interface, which means the connection is successful.

You can see that there are multiple databases, and I use the test library above.

Create a new php file in the defined root directory (D:\phpstudy\PHPTutorial\WWW here). The content is as follows

<?php 

header("Content-Type:text/html;charset=utf-8");//If there is no such sentence, the following Chinese characters display garbled;

//code = $_POST['code'];

$status = "";

$success = "";

$scookies = "";

 

//Connect to the database Use mysqli mode

$username="root";

$userpass="root";

$servername = "localhost";

$dbname = "test";

$conn = "";//Database variables

//Connect to the database function, the parameters are the database address, user name, password, database name

function connectdb($server,$name,$pwd,$databasename)

{

    //Create a connection, connect to the database, and determine whether the connection is successful

    $conn = new mysqli($server,$name,$pwd,$databasename);

    // detect connection

    if ($conn->connect_error) 

    {

        die("link db failire: " . $conn->connect_error);

        echo "connect database [" . $server . " ]  failire <br/>";

        return $conn;

    } 

    else

    {

        echo "connect database [" . $server . "]  successful <br/>";

        return $conn;

    }

}

//Check if the table exists

function check_table_is_exist($sql,$find_table)

{

    $row=mysql_query($sql);

    $database=array();

    $finddatabase=$find_table;

    while ($result=mysql_fetch_array($row,MYSQL_ASSOC))

    {

    $database[]=$result['Database'];

    }

    unset($result,$row);

    mysql_close();

    /*Start to determine whether the table exists*/

    if(in_array($find_table,$database))

    {

    return true;

    }

    else

    {

    return false;

    }

}

//create new table

function createnewtable($conn)

{

    // Use sql to create a data table

    $sql = "CREATE TABLE MyGuests (

    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 

    firstname VARCHAR(30) NOT NULL,

    lastname VARCHAR(30) NOT NULL,

    email VARCHAR(50),

    reg_date TIMESTAMP

    )";

     if ($conn->query($sql) == TRUE) 

     {

         echo  "Table MyGuests created successfully <br/>";

    } 

    else 

    {

        echo  "create database table error: " . $conn->error . " <br/>";

        

        return false;

    }

}

 

function insertrecord($conn,$tablename)

{    

    //echo -e "\r\n";

    //Insert a piece of data

    $sql = "INSERT INTO MyGuests (firstname, lastname, email)

    VALUES ('John', 'Doe', '[email protected]')";

        

    if ($conn->query($sql) == TRUE) 

    {        

        print "insert one record successful <br/>";

        

    } else 

    {

        echo  "Error: " . $sql . "<br/>" . $conn->error;

        echo  "\r\n";

    } 

    $sql="";

    //Insert multiple pieces of data

    $sql .= "INSERT INTO MyGuests (firstname, lastname, email)

    VALUES ('Mary', 'Moe', '[email protected]');";

    $sql .= "INSERT INTO MyGuests (firstname, lastname, email)

    VALUES ('Julie', 'Dooley', '[email protected]')";

    if ($conn->multi_query($sql) == TRUE) {

        echo  "insert records successful. <br/>";

    } else {

        echo  "Error: " . $sql . "<br>" . $conn->error;

    }

    return true;    

}

 

function showtabledata($conn,$sql)

{

    $conn->query($sql);

}

function del_data($conn,$sql)

{

    print $sql . "</br>";

    if($conn->query($sql)==true)

    {

        echo "delete records successful </br>";

    }

    else

    {

        echo "delete records failire </br>";

    }

}

function show_alldata_fromtable($servername,$username,$userpass,$dbname,$tablename)

{

    $conn = mysqli_connect($servername,$username,$userpass,$dbname);

    if(mysqli_connect_errno($conn))

    {

        echo "connect mysql failed " . mysqli_connect_error();

        return;

    }

    

    echo "connect successful<br>";

    //The second step is to set the corresponding character encoding

    //$mysqli->set_charset("utf8");

    //$setting = 'set names utf8';

    //mysqli_query($conn,$setting);

    //echo "query successful <br>" ;//. $conn . $setting;

    

    //The third step is to query

    $sql = 'SELECT * FROM MyGuests';

    //Execute the query statement and return result as the data content

    if($result = mysqli_query($conn,$sql))

    {

        //Get the number of queried records,

        $rowcount = mysqli_num_rows($result);

        echo "return {$rowcount} records <br>";

        

        echo 

        "<center>

            <table>

            <tr>

                <th>Serial number </th>

                <th>姓          </th>

                <th>名          </th>

                <th>Email </th>

                <th>Time and date </th>               

            </tr>

            </table>

        </center>";

        for($i = 0;$i <$rowcount;$i ++)

        {

            //Read one record at a time in order and save it to sqldata

            $sqldata = mysqli_fetch_assoc($result);

            echo     

            "<center>

            <table>            

            <tr>

                <td>".$sqldata['id']."</td>

                <td>".$sqldata['firstname']."</td>

                <td>".$sqldata['lastname']. "</td>

                <td>".$sqldata['email']. "</td>

                <td>".$sqldata['reg_date']. "</td>

            </tr>

            </table>

            </center>";

        }

 

        mysqli_free_result($result);

    }    

   

    //The fifth step is to write the result to the cache file

    $file = "sqlcache.txt";

    $msg = serialize($sqldata);

    //echo $msg;

    $fp = fopen($file,"w");

    fputs($fp,$msg);

    fclose($fp);

}

 

//Connect to the database

$conn = connectdb($servername,$username,$userpass,$dbname);

createnewtable($conn);

$sql = "DELETE FROM myguests ";

//del_data($conn,$sql);

insertrecord($conn,'MyGuests');

//$conn->close();

show_alldata_fromtable($servername,$username,$userpass,$dbname,'',$conn);

$conn->close();

 

?>

Note that the createnewtable function can be executed according to the actual situation;

Through the above files, you can connect to the database, create forms, insert single or multiple records, delete records, display the contents of the database, serialize the contents of the database to a file, and display it on the web page in a simple format;

Here you need to pay attention to the display of line breaks on the web page (I’m going to give it to newbies), to use <br> to achieve, I also tried \n or \r\n at the beginning, took a detour, and recorded it here.

Let's start thinking about how to design an interface. I haven't figured out whether to use php design or js or vue. Record it when you are done.

Guess you like

Origin blog.csdn.net/mainmaster/article/details/114686335