MySQL -PHP相关语句

  • 连接数据库
$dbc = mysql_connect('localhost', 'username', 'password')
  • 发送信封(创建数据库),也可以不用PHP创建
mysql_query('CREATE DATABASE myblog', $dbc)
  • 选中当前数据库,通常用于判断数据库是否可以连接
mysql_select_db('myblog', $dbc)
  • 发送信封(创建数据库表头),同理也可以不用PHP进行创建
$query = 'CREATE TABLE entries (
entry_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
entry TEXT NOT NULL,
date_entered DATETIME NOT NULL
)';
mysql_query($query, $dbc)
  • 发送信封(安全插入数据,对危险字符进行转义)
$title = mysql_real_escape_string(trim(strip_tags($_POST['title'])), $dbc);
$entry = mysql_real_escape_string(trim(strip_tags($_POST['entry'])), $dbc);
$query = "INSERT INTO entries (entry_id, title, entry, date_entered) VALUES (0, '$title', '$entry', NOW())";
mysql_query($query, $dbc)
  • 发送信封(检索数据)
/*该基本查询告诉数据库需要查看entries表中所有行所有列的数据。返回的结果应该进行排序,
和通过ORDER BY 子句指定了按照输入的时间(记录在date_entered列中)进行排序,
最先显示最近插入的记录。语句最后的DESC选项是descending的简写*/
$query = 'SELECT * FROM entries ORDER BY date_entered DESC';
if ($r = mysql_query($query, $dbc)) { // Run the query.

    // Retrieve and print every record:
    while ($row = mysql_fetch_array($r)) {
        print "

{$row['title']}

{$row['entry']}
Edit Delete


\n"; }
  • 发送信封(删除数据)
$query = "DELETE FROM entries WHERE entry_id={$_POST['id']} LIMIT 1";
$r = mysql_query($query, $dbc); 
//检查查询结果
if (mysql_affected_rows($dbc) == 1) {
        print '

The blog entry has been deleted.

'; } else { print '

Could not delete the blog entry because:
' . mysql_error($dbc) . '.

The query being run was: ' . $query . '

'; }
  • 发送信封(更新数据)
$query = "UPDATE entries SET title='$title', entry='$entry' WHERE entry_id={$_POST['id']}";
$r = mysql_query($query, $dbc);
//检测更新结果
if (mysql_affected_rows($dbc) == 1) {
           print '

The blog entry has been updated.

'; } else { print '

Could not update the entry because:
' . mysql_error($dbc) . '.

The query being run was: ' . $query . '

'; }
  • 关闭数据库连接
mysql_close($dbc);

你可能感兴趣的:(MySQL -PHP相关语句)