For PHP beginner users, as long as we master basic database writing, reading, editing, deletion and other basic operations, even if we get started, we can write simple programs, such as message books, news article systems, etc. During the entire process, connection to MySQL database is also relatively important. You can use multiple methods to connect. For novices, we should not analyze which method optimizes the system resources. We can connect first.
Here, we organize several commonly used methods of PHP connecting to MYSQL databases.
First,Common common methods
$mysql_server="localhost"; $mysql_username="Database Username"; $mysql_password="Database Password"; $mysql_database="Database Name"; //Create a database link$conn = mysql_connect($mysql_server,$mysql_username,$mysql_password) or die("Database link error"); //Select a databasemysql_select_db($mysql_database,$conn); mysql_query("set names 'utf8'"); //Execute MySQL statement$result=mysql_query("SELECT id,name FROM database table"); //Extract data$row=mysql_fetch_row($result);
When extracting data, we use mysql_fetch_row, and we can also use mysql_fetch_assoc and mysql_fetch_array. For details, we refer to the manual.
second,Object-oriented method
$db=new mysqli($dbhost,$username,$userpass,$dbdatabase); if(mysqli_connect_error()){ echo 'Could not connect to database.'; exit; } $result=$db->query("SELECT id,name FROM user"); $row=$result->fetch_row();
third,PDO method
$dsn='mysql:host='.$dbhost.';dbname='.$dbdatabase.';' $dbh=new PDO($dsn,$username,$userpass); $stmt=$dbh->query('SELECT id,name FROM user'); $row=$stmt->fetch();
The above are three commonly used methods for connecting to MYSQL databases. We can try it. Generally, we use the first one more.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.