Reputation: 5140
I have the following code:
<?php
$conn = mysqli_connect('localhost', 'root', 'lol', 'api');
$name2 = $session->username;
$nokey = "You don't have an API key.";
$query = mysqli_query($conn, "SELECT * FROM apikey WHERE username = '$name2';");
while($row = mysqli_fetch_array($query)) {
echo "<p>Your API Key: " . $row['apikey'] . "</p>";
}
?>
I an having trouble making it echo $nokey if there username is not in the database. I have tried multiple things but nothing had worked out. Hoping someone here can help.
Upvotes: 1
Views: 123
Reputation: 515
<?php
$servername = "localhost";
$username = "root";
$password = "lol";
$dbname = "api";
$conn = new mysqli($servername, $username, $password, $dbname);
$name2 = $session->username;
$sql = "SELECT * FROM apikey WHERE username = '$name2';";
$query = $conn->query($sql);
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
echo "<p>Your API Key: " . $row['apikey'] . "</p>";
}
}
else{
echo "You don't have an API key.";
}
?>
Try this.
Upvotes: 1
Reputation: 13127
You need to check whether any rows were returned by your query. Something like this should work:
<?php
$conn = mysqli_connect('localhost', 'root', 'lol', 'api');
$name2 = $session->username;
$nokey = "You don't have an API key.";
$query = mysqli_query($conn, "SELECT * FROM apikey WHERE username = '$name2'");
if (mysqli_num_rows($query)) {
while($row = mysqli_fetch_array($query)) {
echo "<p>Your API Key: " . $row['apikey'] . "</p>";
}
} else {
// this is the new bit
echo $nokey;
}
?>
Upvotes: 2
Reputation: 148
Run this code right after $query
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_array($query)) {
echo "<p>Your API Key: " . $row['apikey'] . "</p>";
}
} else {
echo $nokey;
}
Upvotes: 3