PHP is a popular programming language through which databases can be operated. Querying is a common task used to retrieve and obtain information stored in a database. In PHP 5.5.0, executing queries can be completed in the following three ways:
<?php //建立连接 $conn = mysql_connect('localhost', 'root', 'password'); //选择数据库 mysql_select_db('mydb'); //执行查询 $result = mysql_query('SELECT * FROM mytable'); //输出结果 while($row = mysql_fetch_assoc($result)) { echo $row['name'] . ', ' . $row['age'] . "<br>"; } //关闭连接 mysql_close($conn); ?>
However, it should be noted that using mysql functions requires enabling extensions. These functions have been deprecated in PHP7.0. It is recommended to use mysqli or PDO.
<?php //建立连接 $conn = mysqli_connect('localhost', 'root', 'password', 'mydb'); //执行查询 $result = mysqli_query($conn, 'SELECT * FROM mytable'); //输出结果 while($row = mysqli_fetch_assoc($result)) { echo $row['name'] . ', ' . $row['age'] . "<br>"; } //关闭连接 mysqli_close($conn); ?>
It should be noted that the parameters that need to be passed in the mysqli function represent the database address, user name, password, database name, and mysql in order. Functions are different. In addition, the mysqli function provides a safer query method, such as using prepared statement to execute queries, avoiding security issues such as SQL injection.
<?php //建立连接 $dsn = "mysql:host=localhost;dbname=mydb"; $user = "root"; $password = "password"; $pdo = new PDO($dsn, $user, $password); //执行查询 $stmt = $pdo->query('SELECT * FROM mytable'); //输出结果 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['name'] . ', ' . $row['age'] . "<br>"; } //关闭连接 $pdo = null; ?>
It should be noted that when using PDO, you need to first connect to the database through DSN (Data Source Name, data source name). PDO also provides convenient and safe query methods such as automatic escaping and precompiled statements. In addition, it should be noted that each row of data returned by PDO is an array, and the data can be obtained by specifying fetch_style and modifying it to an object or column name only.
The above are sample codes for three different query methods in PHP 5.5.0. It is very important to choose different extensions and query methods for different needs and database platforms. It should be noted that security issues such as SQL injection need to be prevented when querying. This is a necessary means to protect the security of database data.
The above is the detailed content of How to write queries in PHP 5.5.0. For more information, please follow other related articles on the PHP Chinese website!