問題描述
我正在將所有使用 PHP MySQL 的查詢更改為 MySQLi.
I am changing all my queries that are using PHP MySQL to MySQLi.
我用連接設置創建了一個名為 db.php 的文件.
I have made a file called db.php with the connection settings.
文件包含
<?php
$db = new mysqli('localhost','mysqlusername','mysqlpassword');
echo "<h1>Success database connection</h1>";
if($db->connect_errno > 0)
{
die('No connection [' . $db->connect_error . ']');
}
?>
我將文件包含在:
require_once "/location/db.php";
之后我使用:
if($db->connect_error)
{
echo "Not connected, error: ".$db->connect_error;
}
else
{
echo "Connected.";
}
它回顯已連接,所以我認為我的連接良好.
It echo's Connected so I assume my connection is good.
我有 3 個 PHP 變量要插入到我的數據庫表代碼中
I have 3 PHP variables which I want to insert in my database table Code
我首先回顯變量,所以我確定它們有內容.
I first echo the variables so I am sure they have content.
在我驗證我的連接沒問題后(返回 Connected)并回顯我想要查詢的變量的內容:
After I validated my connection is alright (returned Connected) and echoing the content of the variables I want to do the query with:
$sql = "INSERT INTO 'Code' (`Name`, `Code`, `Admin`)
VALUES ('$name', '$code', '$admin')";
echo $sql;//show query
// Performs the $sql query on the server to insert the values
if ($db->query($sql) === TRUE)
{
echo 'User Created.';
}
else
{
echo 'Errorcreating : '. $db->error;
}
我收到消息 Errorcreating : No database selected
I get the message Errorcreating : No database selected
我有 echo $sql 來顯示查詢.
I have the echo $sql to show me the query.
如果我直接在 SQL 中復制查詢,它會像它應該的那樣工作.
If I copy the query directly in SQL it works like it should.
這是我第一次使用 MySQLi,所以我可能犯了一個非常愚蠢的錯誤,但我找不到.
This is my first time on MySQLi so it's possible I made a very dumb mistake but I can't find it.
推薦答案
打開連接時可以傳遞數據庫名稱作為第四個參數:
When opening the connection you can pass the database name as a 4th parameter:
$db = new mysqli('localhost','mysqlusername','mysqlpassword','database');
另外,你的轉義字符是錯誤的.不要在表名周圍使用單引號,而是使用反引號運算符
Also, your escape character is wrong. Don't use single quotes around table names, use backtick operator instead
$sql = "INSERT INTO `Code` (`Name`, `Code`, `Admin`)VALUES ('$name', '$code', '$admin')";
這篇關于沒有選擇數據庫錯誤信息的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!