php 连接数mysql数据库(Mac mamp下)

03. March 2016 PHP 0
<?php
header("Content-Type:text/html;charset=utf-8");
$servername = "localhost";
$username = "root";
$password = "root";
mysql 默认端口为3306,如果修改了端口的值,在连接数据库的时候应加上            $port = 3307;  设置的端口值
 // 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
else{
  echo "连接成功";
}
//Create database---------------------------------
    $sql = "CREATE DATABASE myDB";
   if (mysqli_query($conn, $sql)) {
       echo "Database created successfully";
    } else {
       echo "Error creating database: " . mysqli_error($conn);
  }
$sql = "create table test_li(                     //create table
Id INT  auto_increment PRIMARY  KEY ,
Name VARCHAR (16),
Sex VARCHAR (10),
Age INT
)";
$flage = mysqli_query($conn, $sql);
if (!$flage){
    die('can\'t create table' );
}
mysqli_query($conn, "SET NAMES UTF8"); 设置编码,防止中文插入数据库乱码
$conn->query("SET NAMES UTF8");
$sql = $conn->prepare("insert into test_li (Name,Sex,Age) VALUES (?,?,?)");
$sql->bind_param("ssi",$Name,$Sex,$age);
$Name = "李健";
$Sex = "male";
$age = 200;
$sql->execute();
$sql->close(); 数据预处理,减少分析时间,节约带宽,防止sql注入
$sql = "select * from test_li";
$result = $conn->query($sql);
if ($result->num_rows>0){
 while ($row = $result->fetch_assoc($result)){
  echo $row['Name'];
  echo "<br/>";
 }
}
else{
 echo "select falut";
}

在php5版本之前,一般是用php的mysql函数去驱动mysql数据库的,比如mysql_query()的函数,属于面向过程3、在php5版本以后,增加了mysqli的函数功能,某种意义上讲,它是mysql系统函数的增强版,更稳定更高效更安全,与mysql_query()对应的有mysqli_query(),属于面向对象,用对象的方式操作驱动mysql数据库.


Leave a Reply

Your email address will not be published. Required fields are marked *