创建页面开始连接[code lang="php"]
<?php

$con = mysql_connect("localhost","root","sa"); //新建连接
if (!$con)

{

die('Could not connect: ' . mysql_error()); //判断无法连接错误
}

mysql_select_db("my_db", $con); //选择数据库

$sql="INSERT INTO person (FirstName, LastName, Age) //产生SQL语句
VALUES

('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con)) //判断查询语句结果
{

die('Error: ' . mysql_error());

}

echo "1 record added";

mysql_close($con) //关闭连接
?>

[/code]
网页查询数据
[code lang="php"]<?php

$con = mysql_connect("localhost","peter","abc123"); //创建连接
if (!$con)

{

die('Could not connect: ' . mysql_error()); //判断连接
}

mysql_select_db("my_db", $con); //选择数据库

$result = mysql_query("SELECT * FROM person"); //设定sql查询结果变量

while($row = mysql_fetch_array($result))

{

echo $row['FirstName'] . " " . $row['LastName'];

echo "<br />";

}

mysql_close($con); //关闭连接

?>

[/code]
以html形式输出
[code lang="php"]<?php

$con = mysql_connect("localhost","root","sa");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person"); //定义查询结果变量

echo "<table border='1'> //创建表格边框宽度

<tr>

<th>Firstname</th> //表格
<th>Lastname</th>

</tr>";

while($row = mysql_fetch_array($result)) //遍历结果

{

echo "<tr>";

echo "<td>" . $row['FirstName'] . "</td>";

echo "<td>" . $row['LastName'] . "</td>";

echo "</tr>";

}

echo "</table>";

mysql_close($con);

?>

[/code]

分类: PHP

发表评论