1. Execute SQL statements in PHP
To obtain data from the database, PHP must first execute a SQL statement that operates on the table, including SELECT, INSERT, UPDATE or DELETE statements. Under normal circumstances, when executing a SELECT statement in PHP, some record rows will be found from the table. When executing other statements, only information about whether the statement was successfully executed will be returned.
<?php $host='localhost'; $user_name='root'; $password='helloworld'; $conn=mysql_connect($host,$user_name,$password);//连接MySQL if(!$conn) { die('FAIL!'.mysql_error()); } mysql_select_db('test');//选择数据库 $sql='select UserId,UserName,Gender from users'; $result=mysql_query($sql);//获取查询结果 if($result) { echo 'SQLsyntex:'.$sql.'<br/>Success'; $num=mysql_num_rows($result);//获取查询结果的行数 echo '<br/> select <b>'.$num.' </b>rows'; } mysql_close($conn); ?>
<?php $host='localhost'; $user_name='root'; $password='helloworld'; $conn=mysql_connect($host,$user_name,$password); if(!$conn) { die('FAIL!'.mysql_error()); } mysql_select_db('test'); $sql='select UserId,UserName,Gender,cc from users'; $result=mysql_query($sql) OR die("<br/>ERROR:<b>".mysql_error()."</b><br/><br/><br/>Problem:<br/>.$sql"); if($result) { echo 'SQLsyntex:'.$sql.'<br/>Success'; $num=mysql_num_rows($result); echo '<br/> select <b>'.$num.' </b>rows'; } mysql_close($conn); ?>
After a SQL statement is successfully executed in the program, you can use mysql_fetch_array() to obtain the specific query results, that is, use this function to obtain the field values of the record.
<?php $host='localhost'; $user_name='root'; $password='helloworld'; $conn=mysql_connect($host,$user_name,$password); if(!$conn) { die('FAIL!'.mysql_error()); } mysql_select_db('test'); $sql='select id,name,sex,age from users'; $result=mysql_query($sql) OR die("<br/>ERROR:<b>".mysql_error()."</b><br/><br/><br/>Problem:<br/>.$sql"); if($num=mysql_num_rows($result)) { $row=mysql_fetch_array($result); echo '<pre class="code">'; print_r($row); } mysql_close($conn); ?>
<?php $host='localhost'; $user_name='root'; $password='helloworld'; $conn=mysql_connect($host,$user_name,$password); if(!$conn) { die('FAIL!'.mysql_error()); } mysql_select_db('test'); $sql='select id,name,sex,age from users'; $result=mysql_query($sql) OR die("<br/>ERROR:<b>".mysql_error()."</b><br/><br/><br/>Problem:<br/>.$sql"); if($num=mysql_num_rows($result)) { $row=mysql_fetch_array($result); echo '<pre class="code">'; while($row=mysql_fetch_array($result,MYSQL_ASSOC)) {print_r($row); } } mysql_close($conn); ?>