Home > Article > Backend Development > Example code for php to obtain data from the database
After configuring the PHP environment, we will officially start operating the database! The first is to read the data in MySQL. Remember how we connected to the MySQL database before?
<?php header("Content-type:text/html;charset=utf-8");//字符编码设置 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "web"; // 创建连接 $con =mysqli_connect($servername, $username, $password, $dbname); // 检测连接 $sql = "SELECT * FROM users"; $result = mysqli_query($con,$sql); if (!$result) { printf("Error: %s\n", mysqli_error($con)); exit(); } $jarr = array(); while ($rows=mysqli_fetch_array($result,MYSQL_ASSOC)){ $count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小 for($i=0;$i<$count;$i++){ unset($rows[$i]);//删除冗余数据 } array_push($jarr,$rows); } echo $str=json_encode($jarr);//将数组进行json编码 ?
The above is the detailed content of Example code for php to obtain data from the database. For more information, please follow other related articles on the PHP Chinese website!