简单的MySQL-PHP操作方法
一个简单粗暴的通过GET方法操作MySQL的方法。这里使用的是面向过程的PHP写法:
<?php $servername = "地址"; $username = "用户名"; $password = "密码"; $dbname = "数据库"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); mysqli_set_charset($conn, "utf8"); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //操作标识码 $Flag = $_REQUEST['Flag']; if (!empty($_REQUEST['ID'])){$ID = $_REQUEST['ID'];} if (!empty($_REQUEST['Content'])){$Content = $_REQUEST['Content'];} if (!empty($_REQUEST['Type'])){$Type = $_REQUEST['Type'];} if($Flag == "select") { showinfo(); } if($Flag == "update") { updateinfo(); } if($Flag == "insert") { insert(); } if($Flag == "remove") { remove(); } function showinfo() { global $conn; $sql = mysqli_query($conn,"select * from MyTab"); $result = array(); while($row = mysqli_fetch_object($sql)){ array_push($result, $row); } echo json_encode($result); } function updateinfo() { global $conn; global $Content; global $Type; global $ID; $sql = mysqli_query($conn,"update MyTab set Content='$Content',Type=$Type where ID=$ID"); if ($sql){ echo json_encode(array('success'=>true)); } else { echo json_encode(array('msg'=>'Some errors occured.')); } } function insert() { global $conn; global $Content; global $Type; global $ID; $sql = "insert into MyTab(Content,Type) values('$Content',$Type)"; $result = mysqli_query($conn,$sql); if ($result){ echo json_encode(array('success'=>true)); } else { echo json_encode(array('msg'=>'Some errors occured.')); } } function remove() { global $conn; global $Content; global $Type; global $ID; $sql = "delete from MyTab where ID=$ID"; $result = mysqli_query($conn,$sql); if ($result){ echo json_encode(array('success'=>true)); } else { echo json_encode(array('msg'=>'Some errors occured.')); } } mysqli_close($conn); ?>
客户端直接使用GET方法即可通过PHP连接MySQL。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭