跟着学习PHP相关东西的day2:查询,增删数据、记录

DAY2/建站计划日3

这是第一部分。

 

一组简单的查询、增删数据记录语句

需要先设置好一个本地数据库,数据库名,及用户名均为video,数据库密码是nijigaku。否则会显示权限问题。

A:INDEX.PHP 部分代码

 

<?php
$host=’127.0.0.1′;
$user=’video’;
$password=’nijigaku’;
$dbName=’video’;
$conn = new mysqli($host, $user, $password,$dbName);

if ($conn->connect_error) {
die(“连接失败: ” . $conn->connect_error);
}
echo ‘连接成功<br />’;

$sql=”CREATE TABLE IF NOT EXISTS avnum( “.
“avnum varchar(10) not null,”.
“vdname varchar(100),”.
“PRIMARY KEY ( avnum ))ENGINE=InnoDB DEFAULT CHARSET=utf8;”;
$scd=$conn->query($sql);

if ($scd){
echo ‘创建成功<br />’;
}
?>

<form action=”submit.php” method=”post”>
<label>AV号</label><input name=”avnum” />
<label>视频名</label><input name=”vdname” />
<button type=”submit”>提交</button>
</form>

<?php
if (!empty($_POST[‘avnum’])){
$num=$_POST[‘avnum’];
$name;
if (!empty($_POST[‘vdname’])){
$name=$_POST[‘vdname’];
}
$sql=”select count(*) from avnum where avnum=”.$num.”;”;
$ext=$conn->query($sql);

$i=0;
$results = array();
foreach($ext as $row){
$results[$i] = $row;
$i++;
}

if ($results[0][‘count(*)’]!=0) { echo ‘av号已经存在!<br />’;}
else {
$sql=”INSERT INTO avnum VALUES (‘”.
$num.
“‘,'”.
$name.
“‘);”;

$scd=$conn->query($sql);
}
}
?>

<?php
$sql=”select count(*) from avnum;”;
$cnt=$conn->query($sql);
$sql=”select * from avnum;”;
$data=$conn->query($sql)->fetch_all();

foreach($data as $row){
echo ($row[0]);
echo ” “;
echo ($row[1]);
echo “<br />”;
}
?>

 

B.sumbit.php

<?php
$host=’127.0.0.1′;
$user=’video’;
$password=’nijigaku’;
$dbName=’video’;
$conn = new mysqli($host, $user, $password,$dbName);

if ($conn->connect_error) {
die(“连接失败: ” . $conn->connect_error);
}
echo ‘连接成功<br />’;

$sql=”CREATE TABLE IF NOT EXISTS avnum( “.
“avnum varchar(10) not null,”.
“vdname varchar(100),”.
“PRIMARY KEY ( avnum ))ENGINE=InnoDB DEFAULT CHARSET=utf8;”;
$scd=$conn->query($sql);

if ($scd){
echo ‘创建成功<br />’;
}
?>

<?php
if (!empty($_POST[‘avnum’])){
$num=$_POST[‘avnum’];
$name;
if (!empty($_POST[‘vdname’])){
$name=$_POST[‘vdname’];
}
$sql=”select count(*) from avnum where avnum=”.$num.”;”;
$ext=$conn->query($sql);

$i=0;
$results = array();
foreach($ext as $row){
$results[$i] = $row;
$i++;
}

if ($results[0][‘count(*)’]!=0) { echo ‘av号已经存在!<br />’;}
else {
$sql=”INSERT INTO avnum VALUES (‘”.
$num.
“‘,'”.
$name.
“‘);”;

$scd=$conn->query($sql);

if ($scd){
echo ‘添加成功<br />’;
}
}
}
?>

<form action=”index.php”>
<button type=”submit”>确定</button>
</form>

 

使用PHP study本地架设服务器后的测试结果,如下:

 

结束。接下来PART2.

发表评论