search
HomeBackend DevelopmentPHP Tutorialhtml completes front-end and back-end interaction with php+MySQL

1.php database connection and basic operation configuration
(1)php creates database [connection] (Related mysql video tutorial recommendation: "mysql tutorial")

语法:Object mysqli_connect("域名","DB账号","DB密码","DB库名")
例子:$con = mysqli_connect('localhost','root','','frankdb');

(2) Solution to garbled Chinese characters when inserting data into DB
Syntax:

mysqli_query($con,"set names utf8");

Note: If the setting is successful, 1 will be returned. Depending on the actual situation, it is not necessary to save the returned result.
(3) Set the client and server to keep the character encoding consistent
Syntax:

mysqli_query($con,"set character_set_client=utf8");
    mysqli_query($con,"set character_set_results=utf8");	

(4) Execute sql statement

语法:$结果 = $DB连接->query(sql语句);
例子:var_dump($result = $con->query($sql));

2. Use basic sql statement [template]
a.Establish connection
b.Determine whether to connect
c.Set encoding
d.Create sql statement
eNumber of execution results
g.Patch results
h.jsonized return

<?php
//a.sql 查询语句
无条件查询,即直接写1即可
//$sql=&#39;select * from 哪张表 where 条件&#39;;
有条件查询,在where后面写出查询条件,如果多个条件需要用and 或or 来连接。
//$sql="select stuName from stud  where stuScore=&#39;100&#39; and stuGender=&#39;female&#39;";
//$sql="select stuName from stud  where stuScore=&#39;100&#39; or stuGender=&#39;female&#39;";
        $con=mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;studb&#39;)
        
         if($con){
               echo&#39;<pre class="brush:php;toolbar:false">&#39;;
               echo&#39;数据库连接成功,等待指令...&#39;;
               mysqli_query($con,&#39;set  names utf8&#39;);
               mysqli_query($con,&#39;set  character_set_client=utf8&#39;);
               mysqli_query($con,&#39;set  character_set_results=utf8&#39;);
               $sql="select * from stud where 1";
               $result=$con->query($sql);
               if($result>num_rows>0){
                         $info=[];
                   for($i=0;$row=$result->fet_assoc();$i++){
                                   $info[$i]=$row;
                     }
                     echo json_encode($info);
                  }
               }else{
                    echo&#39;<pre class="brush:php;toolbar:false">&#39;;
                    echo&#39;数据连接失败,请重新连接‘;
              }

b.Insert statement (add statement)
Two ways of writing:

(1)$sql="insert into 表名(字段1,字段2,...)  values(值1,值2,...)";
(2)$sql=&#39;insert into 表名(&#39;值1’,&#39;值2&#39;,...)";
 $con=mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;studb&#39;);
                 if($icon){
                        echo&#39;<pre class="brush:php;toolbar:false">&#39;;
                        echo&#39;数据库连接成功,等待指令...&#39;;
                        mysqli_query($con, &#39;set names utf8&#39;);
                        mysqli_query($con, &#39;set character_set_client=utf8&#39;);
                        mysqli_query($con, &#39;set character_set_result=utf8&#39;);
                        
                        $sql="insert into  stud  stuName,stuGender,stuAge,stuNum,stuScore)values(&#39;lucy&#39;,&#39;female&#39;,&#39;14&#39;,&#39;123456789&#39;,&#39;90&#39;)";
                        $sql="insert into  stud  values(&#39;lucy&#39;,&#39;female&#39;,&#39;14&#39;,&#39;123456789&#39;,&#39;90&#39;)";
                        $result=$con->query($sql);
                            if($result){
                               echo&#39;添加成功&#39;;
                           }else{
                               echo&#39;添加失败&#39;;
                         }

c. Modify statement (update statement) update

$sql="update  表名 set 字段1=‘新值1’,字段2=‘新值2’,... where  条件“;
$con=mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;studb&#39;);
   if($con){
                      
echo "<pre class="brush:php;toolbar:false">";
                echo "数据库连接成功,等待指令...";
                        mysqli_query($con, &#39;set names utf8&#39;);
mysqli_query($con, &#39;set character_set_client=utf8&#39;);
mysqli_query($con, &#39;set character_set_results=utf8&#39;);
$sql="update  stud  set  stuScore=&#39;100&#39; where stuName=&#39;lily&#39;";
$result=$con->query($sql);
var_dump($result);
  }else{
        echo "数据库连接失败!!!";
}

d. Delete statement delete

$sql="delete from 表名 where 条件“;
             $con=mysqli_connect(&#39;localhost&#39;,&#39;toot&#39;,&#39;&#39;;&#39;studb&#39; );
                        if($con){
echo "<pre class="brush:php;toolbar:false">";
echo "数据库连接成功,等待指令...";
//
mysqli_query($con, &#39;set names utf8&#39;);
mysqli_query($con, &#39;set character_set_client=utf8&#39;);
mysqli_query($con, &#39;set character_set_results=utf8&#39;);
//
$sql = "delete from stud where stuName=&#39;lucy&#39;";
$result = $con->query($sql);
var_dump($result);
}else{
echo "数据库连接失败!!!";
}
 
   ?>                      
                         
                         
                ajax & php
                         
         <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<span>姓名:</span><input type="text" class="stuName"><br/>
<span>性别:</span><input type="text" class="stuGender"><br/>
<span>年龄:</span><input type="text" class="stuAge"><br/>
<span>手机:</span><input type="text" class="stuNumber"><br/>
<span>分数:</span><input type="text" class="stuScore"><br/>
<button>增:将上述信息添加至数据库</button><br/>
<button>删:根据姓名删除指定的内容</button><br/>
<button>改:根据姓名修改指定的内容</button><br/>
<button>查:查询数据库中所有的内容</button>
<!-- 1.引入jquery框架 -->
<script src="jquery-1.12.3.min.js"></script>
<script>
$(&#39;button:eq(0)&#39;).click(function(){
//2.在想要和后台交互的时候,调用$.ajax()方法
//参数是JSON格式
$.ajax({
//3.ajax结构需要一系列参数支持
type:&#39;post&#39;,//get|post
url:&#39;http://127.0.0.1/day3/code/lesson6_ajax&php/lesson6_ajax&php.php&#39;,
dataType:&#39;json&#39;,
data:{
//data是post请求独有的,因为post请求才需要携带数据给后台
stuName:$(&#39;.stuName&#39;).val(),
stuGender:$(&#39;.stuGender&#39;).val(),
stuAge:$(&#39;.stuAge&#39;).val(),
stuNumber:$(&#39;.stuNumber&#39;).val(),
stuScore:$(&#39;.stuScore&#39;).val(),
},
//请求完成后,若收到后台返回的数据(收到响应response),这个函数会被自动执行。
success:function(data){
console.log(data);
}
});
});
$(&#39;button:eq(1)&#39;).click(function(){
});
$(&#39;button:eq(2)&#39;).click(function(){
});
$(&#39;button:eq(3)&#39;).click(function(){
});
</script>
</body>
</html>
   <?php             
  
/*
1.内置对象
在php中内置了两个对象用来接收,前端发来的信息。
$_GET 和 $_POST
$_GET用于获取在前端通过get请求发来的信息
$_POST用于获取在前端通过post请求发来的信息
*/
echo json_encode($_POST);
?>                       
                         
        ajax select&php 
        
                   
                    <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<span>姓名:</span><input type="text" class="stuName"><br/>
<span>性别:</span><input type="text" class="stuGender"><br/>
<span>年龄:</span><input type="text" class="stuAge"><br/>
<span>手机:</span><input type="text" class="stuNumber"><br/>
<span>分数:</span><input type="text" class="stuScore"><br/>
<button>增:将上述信息添加至数据库</button><br/>
<button>删:根据姓名删除指定的内容</button><br/>
<button>改:根据姓名修改指定的内容</button><br/>
<button>查:查询数据库中所有的内容</button>
<script src="jquery-1.12.3.min.js"></script>
<script>
$(&#39;button:eq(0)&#39;).click(function(){
//判空操作
var stuNameValue = $(&#39;.stuName&#39;).val();
var stuGenderValue = $(&#39;.stuGender&#39;).val();
var stuAgeValue = $(&#39;.stuAge&#39;).val();
var stuNumberValue = $(&#39;.stuNumber&#39;).val();
var stuScoreValue = $(&#39;.stuScore&#39;).val();
if(
stuNameValue.length==0||
stuGenderValue.length==0||
stuAgeValue.length==0||
stuNumberValue.length==0||
stuScoreValue.length==0){
alert(&#39;任意某一个输入信息都不能为空!&#39;);
return;
}
$.ajax({
type:&#39;post&#39;,
url:&#39;http://127.0.0.1/day3/code/lesson7_html&php&mysql/lesson7_html&php&mysql.php&#39;,
dataType:&#39;json&#39;,
data:{
stuName:$(&#39;.stuName&#39;).val(),
stuGender:$(&#39;.stuGender&#39;).val(),
stuAge:$(&#39;.stuAge&#39;).val(),
stuNumber:$(&#39;.stuNumber&#39;).val(),
stuScore:$(&#39;.stuScore&#39;).val(),
},
success:function(data){
console.log(data);
if(data.msg==&#39;add success&#39;){
alert(&#39;添加成功&#39;);
}else{
alert(&#39;添加失败&#39;);
}
}
});
});
$(&#39;button:eq(1)&#39;).click(function(){
});
$(&#39;button:eq(2)&#39;).click(function(){
});
$(&#39;button:eq(3)&#39;).click(function(){
$.ajax({
type:&#39;get&#39;,
url:&#39;http://127.0.0.1/day3/code/lesson7_html&php&mysql/lesson7_select.php&#39;,
dataType:&#39;json&#39;,
success:function (data){
console.log(data);
},
error: function (err){
console.log(err);
}
});
});
</script>
</body>
</html>
     
                         
   <?php
//查询功能的后台php文件
$success = array(&#39;status&#39; => &#39;success&#39;);
$error = array(&#39;status&#39; => &#39;error&#39;);
$con = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;studb&#39;);
if($con){
mysqli_query($con, &#39;set names utf8&#39;);
mysqli_query($con, &#39;set character_set_client=utf8&#39;);
mysqli_query($con, &#39;set character_set_results=utf8&#39;);
$sql = "select * from gradeonesheet where 1";
$result = $con->query($sql);
if($result->num_rows>0){
$info = [];
for($i=0; $row=$result->fetch_assoc(); $i++){
$info[$i] = $row;
}
//
echo json_encode($info);
}
}
?>             
<?php
//添加数据的
$success = array(&#39;status&#39; => &#39;OK&#39;);
$error = array(&#39;status&#39; => &#39;error&#39;);
$con = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;,&#39;studb&#39;);
if($con){
mysqli_query($con, &#39;set names utf8&#39;);
mysqli_query($con, &#39;set character_set_client=utf8&#39;);
mysqli_query($con, &#39;set character_set_results=utf8&#39;);
//
$stuName = $_POST[&#39;stuName&#39;];
$stuGender = $_POST[&#39;stuGender&#39;];
$stuAge = $_POST[&#39;stuAge&#39;];
$stuNumber = $_POST[&#39;stuNumber&#39;];
$stuScore = $_POST[&#39;stuScore&#39;];
$sql = "insert into gradeonesheet values(&#39;$stuName&#39;,&#39;$stuGender&#39;,&#39;$stuAge&#39;,&#39;$stuNumber&#39;,&#39;$stuScore&#39;)";
$result = $con->query($sql);
if($result){
$success[&#39;msg&#39;] = &#39;add success&#39;;
echo json_encode($success);
}else{
$error[&#39;msg&#39;] = &#39;add failed&#39;;
echo json_encode($error);
}
}else{
$error[&#39;msg&#39;] = &#39;database connect failed&#39;;
echo json_encode($error);
}
?>

Related recommendations:

php mysql develops the simplest online question bank and online question making system


The above is the detailed content of html completes front-end and back-end interaction with php+MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor