PHP connects to MySql database
Here I will introduce the mysqli of PHP. This command can be used for both object-oriented programming and procedural programming. Using pre-compiling can effectively prevent SQL injection problems. Give an example code directly (the following code is not precompiled, object-oriented):
<?php $conn=new mysqli("localhost","root","root","test"); $conn->query("set names 'utf8'"); $sql="INSERT INTO `user` (`name`,`password`) VALUE (\"Peter\",\"123456\")"; if($conn->query($sql)) echo "操作成功"; else echo "操作失败"; $conn->close(); ?>
(The code below is precompiled and object-oriented)
<?php $conn = new mysqli ( "localhost" , "root" , "root" , "test" ) ; //Database address, username, password, database name $conn - > query ( "set names 'utf8'" ) ; //Modify the character set $sql = "INSERT INTO `user` (`name`,`password`) VALUE (?,?)" ; //SQL statement, the question mark is the parameter to be bound after precompile $conn_stmt = $conn - > prepare ( $sql ) ; //precompile $comm_stmt - >bind_param("ss", $name , $pass ) ; //Binding parameters $name = "Peter" ; #pass = "123456" ; //Prompt that the actual operation does not need such a simple password if ( $conn_stmt - > execute ( ) ) echo " The operation succeeded" ; else echo "The operation failed" ; //Execute and judge the result $conn_stmt - > close ( ) ; //Close the precompiled $conn - > close ( ) ; //Close the connection ? >
//Use the procedure-oriented method to connect to the database $conn = mysqli_connect( "gxyiovmx.2365.dnstoo.com" , "dingyifeng_f" , "zxcvbn" , "dingyifeng" ) ; //Use the object-oriented method to connect to the database $db = new mysqli( "gxyiovmx.2365.dnstoo.com" , "dingyifeng_f" , "zxcvbn" , "dingyifeng" ) ; //Use PDO to link the database $dsn = 'mysql:host=' . 'gxyiovmx.2365.dnstoo.com' . ';dbname=' . 'dingyifeng' . ';'; $dbh=new PDO($dsn,"dingyifeng_f","zxcvbn");