mysql连接操作
//建立连接
$con = mysql_connect(‘localhost‘, ‘root‘, ‘123456‘);
//判断是否连接成功
if($con){
die(‘连接失败!‘.mysql_error());
exit;
}
//选择字符集
mysql_set_charset(‘utf8‘, $con);
//选择数据库
mysql_select_db(‘test‘, $con);
$sql = ‘.........................‘;
//执行sql语句
$result = mysql_query($sql, $con);
//如果是插入操作
mysql_affected_rows() 获取影响行数
mysql_insert_id() 获取新插入的ID
//如果是查询操作
while($row = mysql_fetch_assoc($result)){
echo ‘<pre>‘;
var_dump($row);
echo ‘</pre>‘;
}
//关闭数据库
mysql_close($con);
1 //数据库连接 2 function mysqlConnect(){ 3 $con = mysql_connect("localhost", "root", ""); 4 if(!$con){ 5 die("连接失败!".mysql_error()); 6 exit; 7 } 8 9 mysql_set_charset("utf8", $con); 10 mysql_select_db("ms", $con); 11 12 /* 13 $sql = "select * from user;"; 14 $result = mysql_query($sql); 15 16 if(mysql_num_rows($result)){ 17 while($rows = mysql_fetch_assoc($result)){ 18 echo ‘<pre>‘; 19 var_dump($rows); 20 echo ‘</pre>‘; 21 } 22 } 23 */ 24 25 $sql = "insert into user (username) values (‘test123‘)"; 26 $result = mysql_query($sql); 27 28 if($result && mysql_affected_rows()>0){ 29 echo "插入成功!".mysql_insert_id(); 30 } 31 32 mysql_close($con); 33 }
时间: 2024-10-29 19:10:05