>insert
<pre name="code" class="php"><span style="font-size:14px;"><?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?></span>
//mysql_query()的第二个数据库连接参数可以省略,默认使用最近的连接
//感觉json就能起到一个小型数据库的功能。
>>前端界面
<span style="font-size:14px;"><html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
</span>
//当点击html表单时,提交到insert.php。insert.php连接数据库,把数据插入到数据库中,感觉很神奇啊。>查询语句
<span style="font-size:14px;"><?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 Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?></span>
//解释,mysql_fetch_array()函数以数组的形式返回记录集的第一行,每次随后对mysql_fetch_array()函数的调用,都会返回记录集的下一行。
//while loop语句会循环记录集中的所有记录
//为了输出每行的值。我们使用了PHP的$row变量,这个全局变量会记录数据库数组的键值对
>带有条件的查询语句where,条件主要对记录进行筛选。
<span style="font-size:14px;"><?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 Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?></span>
>OERDER BY对记录按照主键或者其他方式排序输出
<span style="font-size:14px;"><?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 Persons ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
</span>?>