上午: Python程式設計
延續昨日課程,今日從流程控制開始,課程中老師也有出幾個練習題讓同學試著自己coding,都算滿簡單的練習 Python流程控制:
下午: 人工智慧與機器學習概論
今天老師教學如何透過php連結SQL,將資料寫入DB或是從DB讀取資料:
寫入DB
<?php
//step 1: connect db
if (!empty($_GET['value'])) {
$myvalue=$_GET['value'];
} else{
$myvalue=NULL;
}
$mysqli = new mysqli("localhost","test123","test123","aiotdb");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
} else {
print "Success! " ;
}
//step 2: sql query
if ($myvalue!=NULL){
if ($result = $mysqli -> query("insert into sensors (value) values ($myvalue)")) {
echo "New value ". $myvalue ." has been added.: " ;
}else{
echo "nothing added!";
}
}
//step 3: disconnect db
$mysqli -> close();
?>
將DB資料轉成JSON
<?php
//step 1: connect db
$mysqli = new mysqli("localhost","test123","test123","aiotdb");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
//step 2: sql query
if ($result = $mysqli -> query("select * from sensors")) {
}
//step 3: fetch array from $result
$data=[];
$index= 0;
while($row = $result -> fetch_array(MYSQLI_NUM)){
$data[$index]=$row;
$index=$index+1;
}
//step 4: ecode json
echo json_encode($data);
//step 5: disconnect db
$mysqli -> close();
?>