<?php
$host = localhost;
$database = test;
$username = root;
$password = root;
$selectName = harry;
//要查询的用户名,通常是用户输入的信息
$insertName = testname;
$connection = mysql_connect($host, $username, $password);
//连接到数据库
mysql_query("set names utf8");
//编码转化
if (!$connection) {
die("could not connect to the database.\n" . mysql_error());
//诊断连接错误
}
$selectedDb = mysql_select_db($database);
//选取数据库
if (!$selectedDb) {
die("could not to the database\n" . mysql_error());
}
$selectName = mysql_real_escape_string($selectName);
//防止SQL注入
$query = "select * from user where name = $selectName";
//构建查找语句
$result = mysql_query($query);
//执行查找
if (!$result) {
die("could not to the database\n" . mysql_error());
}
while ($row = mysql_fetch_row($result)) {
//取出结果并表示
$name = $row[0];
$age = $row[1];
echo "Name: $name Age: $age \n";
}
//添加记录
$insertName = mysql_real_escape_string($insertName);
//防止SQL注入
$insertSql = "insert into user(name, age) values($insertName, 18)";
$result = mysql_query($insertSql);
echo $result . "\n";
//更新记录
$updateSql = "update user set age = 19 where name=$insertName";
$result = mysql_query($updateSql);
echo $result . "\n";
//删除记录
$deleteSql = "delete from user where age = 19";
$result = mysql_query($deleteSql);
echo $result . "\n";
mysql_close($connection);
//关闭连接
|