PHP+MySQL:測試連接+基本DB操作

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   資料   ar   

PHP使用MySQL,從串連、建立、到結果顯示

 1 <?php 2     //串連MySQL測試 3     $db = mysql_connect("localhost","root","wenwen"); 4     if (!$db) 5     { 6           die(‘Could not connect: ‘ . mysql_error()); 7     } 8     else 9     {10         echo "connect success!";11     }12 13     //建立資料庫14     if (!mysql_query("CREATE DATABASE my_db",$db))15     {16         echo "Error creating database: " . mysql_error();17     }18 19     //選擇資料庫20     mysql_select_db("my_db", $db);21 22     //建立表23     $sql = "CREATE TABLE Persons 24     (25         FirstName varchar(15),26         LastName varchar(15),27         Age int28     )";29     mysql_query($sql,$db);30 31     //插入資料32     mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 33     VALUES (‘Jordan‘, ‘Michael‘, ‘51‘)");34     mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 35     VALUES (‘Bryant‘, ‘Kobe‘, ‘36‘)");36 37     //建立結果集38     $sql = "SELECT * FROM Persons";39     $result = mysql_query($sql); 40 41     //在 HTML 表格中顯示結果42     echo "<table border=‘1‘>43     <tr>44     <th>FirstName</th>45     <th>LastName</th>46     <th>Age</th>47     </tr>";48 49     while($rs = mysql_fetch_array($result))50     {51         echo "<tr>";52         echo "<td>" . $rs[‘FirstName‘] . "</td>";53         echo "<td>" . $rs[‘LastName‘] . "</td>";54             echo "<td>" . $rs[‘Age‘] . "</td>";55         echo "</tr>";56     }57     echo "</table>";58 59     //關閉串連60     mysql_close($db);61 ?>

運行效果

DB中的變化

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.