$servername = "127.0.0.1";
$username = "root";
$password = "abc1510360132";
// 创建连接
$conn = new mysqli($servername, $username, $password);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
PDO:php data object ,数据库代码的php封装
$dbms='mysql'; //数据库类型
$host='127.0.0.1'; //数据库主机名
$dbName='mysql'; //使用的数据库
$user='root'; //数据库连接用户名
$pass='12345678'; //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";
try {
$dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
echo "连接成功
";
/*你还可以进行一次搜索操作
foreach ($dbh->query('SELECT * from FOO') as $row) {
print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
}
*/
$dbh = null;
} catch (PDOException $e) {
die ("Error!: " . $e->getMessage() . "
");
}
//默认的是短链接,如果需要长链接
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
?>
1、创建表:
$sql = "CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
number VARCHAR(30) NOT NULL,
email VARCHAR(30),
xueli VARCHAR(30),
num1 INT(6),
num2 INT(6),
adr VARCHAR(30)
)";
$dbh->exec($sql);
2.插入数据:
$sql = "insert into student values(
null,'yanhe',1,'[email protected]','大学本科',100,600,'苹果园'
)";
$res= $dbh->exec($sql);
echo "成功插入了{$res}条数据"
3.查询:
$sql = "select * from student";
foreach ($dbh->query($sql) as $row) {
print $row['name'] . "\t";
}