PHP基础

PHP基础

这两天有个课程项目需要用PHP操作下数据库,学习完简单总结下PHP基本语法,以及操作数据库的代码,方便复用。

基本语法

一些最基本的语法,比如流程控制语句等。

常量

<?php
define('PI',3.1415926);
echo "The value of PI is " . PI;  # user dot to cancat
?>

If语句

<?php
$t = data("H");
if ($t < "10") {
    echo "Have a good moring!";
} elseif ($t < "20") {
    echo "Have a good day!";
} else {
    echo "Have a good night!";
}
?>

While 循环

<?php
$x = 1;
while($x <= 5) {
    echo "Number is : $x <br>";
    $x++;
}
// do while
$y = 1;
do {
    echo "Number is : $y <br>";
    $y++;
} while ($y <= 5); // execute at least once
?>

For循环

<?php
// init counter, test counter, increment counter
for($x=0; $x<= 10; $x++) {
    echo "The number is : $x <br>";
}
// foreach for arrays, loop key/value pair
$colors = array("red", "green", "blue", "yellow");
foreach($colors as $value) {
    echo "$value <br>";
}
?>

Function

<?php
function addNumbers($num1,$num2) {
    return $num1 + $num2;
}
echo "3 + 4 = " . addNumbers(3,4);
?>

操作数据库

PHP一个重要的用途就是操作数据库喽,W3schools有教程可以参考。

连接

基本的连接,查询,commit,rollback等语句。

<?php
// connect and check
$conn = mysqli_connect("127.0.0.1","user","passwd","database");
if (mysqli_connect_errno()){ //return last connection error code 
    echo "Failed to connect: " . mysqli_connect_error(); // return connection error desc
}

// query and commit
mysqli_autocommit($conn,FALSE); // turn off auto commit
mysqli_query($conn,"INSERT INTO Persons (Name, Age) VALUES ('Peter',35)"); // execute query
mysqli_commit($conn); // commit change
// mysqli_rollback($conn); rollback
mysqli_close($conn); // close connection
?>

Query

<?php
/// Perform queries against the database:
mysqli_query($con,"SELECT * FROM Persons");
?>

Fetch Row One by One

Fetch array(numeric or associative)

<?php
$sql = "SELECT Name, Age FROM Persons";
$results = mysqli_query($conn,$sql);
// numeric array
$row = mysqli_fetch_array($results,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// associative array
$row = mysqli_fetch_array($results,MYSQL_ASSOC);
printf ("%s (%s)\n",$row["Name"],$row["Age"]);
// free results set
mysqli_free_result($results); mysqli_close($conn);
?>

Associative

<?php
$row = mysqli_fetch_assoc($results);
printf ("%s (%s)\n",$row["Name"],$row["Age"]);
// while loop through
while($row = mysqli_fetch_assoc($results)) {
    echo $row['Name'] . ':' . $row['Age'];
}
mysqli_free_result($result); mysqli_close($conn);
?>

Fetch All Rows

<?php
// mysqli_fetch_all
// Fetch all rows and return the result-set as an array
$rows = mysqli_fetch_all($results,MYSQL_ASSOC); // or MYSQL_NUM
foreach($rows as $row) {
    echo $row['Name'] . ':' . $row['Age'];
}
?>

Row Count

<?php
$rowcount = mysqli_num_rows($result); // row count
?>

嵌入HTML中

Connect Database

<?php
$conn = mysqli_connect($db_server, $db_user, $db_passwd, $db_name);
$sql = "SELECT name FROM artist ORDER BY listeners DESC";
$rst = mysqli_query($conn, $sql);
?>

嵌入代码

<?= ?>把PHP变量值输出到HTML中。

<div class="list-group">
  <?php foreach(mysqli_fetch_all($rst,MYSQL_ASSOC) as $row): ?>
    <a href="#"> <?= $row['name']? > </a> // use <?= ?> to retrive value from var
  <?php endforeach ?>
</div>

Pass Param to SQL Statement

<?php
$sql = "SELECT name, url FROM artist WHERE name=\"{$_GET['artist']}\""; // get string
$sql = "SELECT name, url FROM artist WHERE id={$_GET['id']}"; // get number
?>

Link to Page with Param

<?php
// use ?var=data get method
<a href='page.php?var=data'>Data link</a>;
// retrive data 
echo $_GET['var'];
?>

Form Handling

从提交的表单中提取信息。

<?php echo $_POST["name"]; ?>
<?php echo $_GET["email"]; ?>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏陈仁松博客

ASP.NET Core 'Microsoft.Win32.Registry' 错误修复

今天在发布Asp.net Core应用到Azure的时候出现错误InvalidOperationException: Cannot find compilati...

4798
来自专栏Golang语言社区

【Golang语言社区】GO1.9 map并发安全测试

var m sync.Map //全局 func maintest() { // 第一个 YongHuomap := make(map[st...

4658
来自专栏Ceph对象存储方案

Luminous版本PG 分布调优

Luminous版本开始新增的balancer模块在PG分布优化方面效果非常明显,操作也非常简便,强烈推荐各位在集群上线之前进行这一操作,能够极大的提升整个集群...

3035
来自专栏C#

DotNet加密方式解析--非对称加密

    新年新气象,也希望新年可以挣大钱。不管今年年底会不会跟去年一样,满怀抱负却又壮志未酬。(不过没事,我已为各位卜上一卦,卦象显示各位都能挣钱...)...

4798
来自专栏我和未来有约会

Kit 3D 更新

Kit3D is a 3D graphics engine written for Microsoft Silverlight. Kit3D was inita...

2506
来自专栏大内老A

The .NET of Tomorrow

Ed Charbeneau(http://developer.telerik.com/featured/the-net-of-tomorrow/) Exciti...

30810
来自专栏pangguoming

Spring Boot集成JasperReports生成PDF文档

由于工作需要,要实现后端根据模板动态填充数据生成PDF文档,通过技术选型,使用Ireport5.6来设计模板,结合JasperReports5.6工具库来调用渲...

1.2K7
来自专栏杨龙飞前端

scrollto 到指定位置

2494
来自专栏闻道于事

js登录滑动验证,不滑动无法登陆

js的判断这里是根据滑块的位置进行判断,应该是用一个flag判断 <%@ page language="java" contentType="text/html...

6588
来自专栏张善友的专栏

LINQ via C# 系列文章

LINQ via C# Recently I am giving a series of talk on LINQ. the name “LINQ via C...

2605

扫码关注云+社区