php基本篇之——mysql

1、使用php获取数据库数据并显示结果的一个脚本

<?php

$link = mysqli_connect("localhost", "root", "111111", "testDB");


/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}


$query = "SELECT * FROM studentinfo";
$result = mysqli_query($link, $query);

echo "<pre>";   //php在网页上显示时格式化了多余的空格和换行符。因此必须要用<pre>元素使格式符可见。

while($field = mysqli_fetch_field($result))  //使用while输出表头

{
printf("%-10s\t",$field->name);
}
echo "<hr>";
while($row = mysqli_fetch_row($result))  //使用while遍历结果值
{
echo "<br/>";
for($i=0;$i<count($row);$i++)
{
printf ("%-10s\t", $row[$i]);  
}

}
echo "</pre>";
/* free result set */
mysqli_free_result($row);


/* close connection */
mysqli_close($link);

?>

显示如下:


2、使用php插入数据简单程序

mysqlinsert.html程序如下:
<html>
<head>
<title> 数据库输入程序</title>
</head>
<body>
<form action="test.php" method="POST">
<p><label for="stuid">id to add</label><br/>
<input type="text" id="stuid" name="stuid" /></p>
<p><label for="stuname">name to add</label><br/>
<input type="text" id="stuname" name="stuname" /></p>
<p><label for="m1">m1 to add</label><br/>
<input type="text" id="m1" name="m1" /></p>
<p><label for="m2">m2 to add</label><br/>
<input type="text" id="m2" name="m2" /></p>
<p><label for="m3">m3 to add</label><br/>
<input type="text" id="m3" name="m3" /></p>
<button type="submit" name="submit" value="insert">insert info</button>
</form>
</body>
</html>

mysqlinsert.php

<?php
$con= mysqli_connect("localhost","root","111111","testDB");
if(!$con)
{
printf("connect failed:%s\n",mysqli_connect_error());
exit();
}
else
{
printf("host information:%s\n",mysqli_get_host_info($con));
}
echo "<br/>";


$id=mysqli_real_escape_string($con,$_POST['stuid']);     // 转义 SQL 语句中使用的字符串中的特殊字符,如空格等等
$name=mysqli_real_escape_string($con,$_POST['stuname']);
$math=mysqli_real_escape_string($con,$_POST['m1']);
$english=mysqli_real_escape_string($con,$_POST['m2']);
$computer=mysqli_real_escape_string($con,$_POST['m3']);


$sql="insert into studentinfo values($id,'$name',$math,$english,$computer)";
$res=mysqli_query($con,$sql);
if($res==TRUE)
{
printf("one record has been inserted!");
}
else
{
printf("could not insert record:%s\n",mysqli_error($con));
}
mysqli_close($con);
?>
html插入显示如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值