2015-11-29 46 views
2

請檢查此代碼,並讓我知道它是否有任何錯誤。SQL查詢有些問題

// Create connection 
$conn = mysqli_connect($servername, $username, $password, $shop_item); 
// Check connection 
if (!$conn) { 
die("Connection failed: " . mysqli_connect_error()); 
} 
$item_sql = "SELECT * FROM shop-items"; 
mysqli_query($conn, 'SET CHARACTER SET utf8;'); 
$result_item = mysqli_query($conn, $item_sql); 

echo var_dump($result_item); //returns: bool(false) 
if (mysqli_num_rows($result_item) > 0) { // doesn't execute. the error is "mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean"; 
+0

絕對'商店項目'認爲像'商店減項' –

+0

謝謝。我嘗試了「SELECT * FROM'shop-items'的phpmyadmin查詢,並執行了這項工作。 –

回答

1

它可以更好地使用類似這樣的結構:

$conn = new mysqli('localhost', 'root', 'password', 'your_database'); 
// Check connection 

if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql="SELECT * FROM shop-items"; 

if ($result = $conn->query($sql)) {  
    // actions in case of success  
} else { 
    echo "Error: " . $sql . "<br>" . $conn->error; 
} 
+0

這仍然會導致錯誤。 –

+0

以及錯誤肯定不是由於PHP結構。你得到了什麼樣的mysql錯誤? – pavlovich

1

這可能是與儀表板的問題。你試過

SELECT * FROM `shop-items` 
+0

是的。謝謝。正確的查詢是「SELECT * FROM'shop-items'」。 –

4

正如我所提到shop-items是由MySQL視爲。 如果你的表名是真的shop-items - 你應該使用反引號進行轉義:

$item_sql = "SELECT * FROM `shop-items`"; 

和檢查錯誤,你可以使用mysqli_error()功能:

$err = mysqli_error($conn); 
echo $err; 
1

我會嘗試使用下面的代碼我所有的查詢從PHP到你的數據庫,因爲有人提到你正在使用什麼錯誤可能會發生從不語法:

$mysqli = new mysqli("localhost", "user", "password", "DB"); 

/* Check conection */ 
if (mysqli_connect_errno()) { 
    printf("Conection error: %s\n", mysqli_connect_error()); 
    exit(); 
} 

$query = "SELECT * FROM shop-items"; 

if ($stmt= $mysqli->prepare($query)) { 

    /* execute the query */ 
    $stmt->execute(); 

    /* Bind the results to variables */ 
    $stmt->bind_result($col1, $col2); //as many variables as columns the query will return 

    /* obtener los valores */ 
    while ($stmt->fetch()) { 
     //do something with the results 
    } 

    /* close the query */ 
    $stmt->close(); 
} 

/* close the DB connection */ 
$mysqli->close(); 
?> 

希望這有助於!