Reputation: 55
I've hit a problem with php script that I'm trying out. When I start it up the script connects to MySQL and the database perfectly, but when I try and select data from the 'codes' database then it gives me an error like this:
Could not get data:
How can I make it say
Could not get data: (then the error here)
instead?
PHP Code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = 'SELECT code FROM codes';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Code:{$row['code']}";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Upvotes: 0
Views: 209
Reputation: 462
You mixed both mysql and mysqli together so i fixed error:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "table";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$sql = 'SELECT username FROM users';
$retval = mysqli_query($conn ,$sql);
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row=mysqli_fetch_array($retval,MYSQLI_ASSOC)) {
echo "Code:{$row['username']}";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
?>
Upvotes: 2