- A+
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php header("content-type:text/html;charset=utf-8"); // error_reporting(0); $link=@mysqli_connect('127.0.0.1','root','root','security'); var_dump($link); echo "<hr>"; if (!$link){ echo "数据库连接错误"; exit(); }else { echo "数据库连接成功"."<br>"; mysqli_query($link ,"set names utf8"); } |
连接成功
连接失败
执行sql语句
1 2 |
$sql="select * from users"; $a=mysqli_query($link, $sql); |
返回结果
从结果集中取一行作为关联数组
1 2 |
$row=mysqli_fetch_assoc($a); echo $row['password']."---".$row['username']; |
从结果集中取得一行作为关联数组,或者数字数组,或者二者兼得
1 2 3 |
$row=mysqli_fetch_array($a); var_dump($row); echo $row['password']."---".$row['username']; |
从结果集中取得一行,并作为枚举数组返回
1 2 |
$row=mysqli_fetch_row($a); var_dump($row); |
1 2 3 4 5 |
// var_dump($row); foreach ($row as $key => $value) { # code... echo $key."----".$value."<br>"; } |
将一行取回到一个对象中,然后通过类的方式取值
1 2 |
$row=mysqli_fetch_object($a); var_dump($row) |
1 2 3 4 5 6 7 8 |
if ($result=mysqli_query($link,$sql)){ while ($obj=mysqli_fetch_object($result)){ printf("%s:%s",$obj->password,$obj->username); echo "<br>"; } mysqli_free_result($result); } |
对象连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php header("content-type:text/html;charset=utf-8"); $mysql=new mysqli("localhost","root","root","security"); var_dump($mysql); echo "<hr>"; var_dump($mysql->server_info); //$mysql->query("set names utf8"); $mysql->set_charset("utf8"); $sql="select * from users"; $result=$mysql->query($sql); //var_dump($result->fetch_assoc()); $data=array(); while ($row=$result->fetch_assoc()) { $data[]=$row; } var_dump($data); ?> |
pdo连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php /* Connect to an ODBC database using driver invocation */ $dsn = 'mysql:dbname=security;host=127.0.0.1'; $user = 'root'; $password = 'root'; try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } $sql="select * from users"; $res=$dbh->query($sql); var_dump($res); $array=$res->fetchAll(); var_dump($array); |
- 我的微信
- 这是我的微信扫一扫
- 我的微信公众号
- 我的微信公众号扫一扫