user3530458
user3530458

Reputation: 3

mysql_query how to display html for if condition

So I have this rustic and basic php that will check a value in my database and if its corrects it will pull out the rest of that row I guess but my problem is how to echo certaine html if the result is okay and how to echo some other html if else.

btw atm else is not working, in other words if you input a code that is not on my db it will not show anything

<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';


// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to 
connect to database! Please try again later.");

// Select the database.
mysql_select_db($db_database)
    or die("Unable to select database: " . mysql_error());

$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
    $result = mysql_query($query);
    if ($result) {
        while($row = mysql_fetch_array($result)) {
                $name = $row["$field"];
                $test = $row["$test"];
                echo "Hello: $name $test";
            }
    }
    else {
        echo "Im sorry you buddy, you are not a winner this time! $test";
    }
   mysql_close($connection);
?>  

Upvotes: 0

Views: 570

Answers (5)

Sadikhasan
Sadikhasan

Reputation: 18600

First you have to correct syntax of database selection like this

mysql_select_db($db_database,$connection);

Insted of

mysql_select_db($db_database);

Check Manual

Upvotes: 0

Karuppiah RK
Karuppiah RK

Reputation: 3964

if(mysql_num_rows($result) > 0) { echo "output"; } else { echo "error msg"; }

Upvotes: 0

arnabkaycee
arnabkaycee

Reputation: 1644

Instead of echoing every html value you can simply enclose html in if statements

like:

<?php
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
    while($row = mysql_fetch_array($result)) {
            $name = $row["$field"];
            $test = $row["$test"];
?>
<b>Hello: <?php echo $name $test"; ?></b>
<?php
        }
}
else {
?>
    <b> Im sorry you buddy, you are not a winner this time! </b> <?php echo $test"; 
}
mysql_close($connection);
?>

Upvotes: 0

Navneil Naicker
Navneil Naicker

Reputation: 3691

You can use mysql_num_rows(), it's the best way.

if( mysql_num_rows($result) > 0 ){
/* Anything you want here on success */
} else {
/* Anything you want here on failure */
}

Upvotes: 1

Thomas
Thomas

Reputation: 1401

Use mysql_num_rows against the query.

if(mysql_num_rows($result)){ } else { }

Upvotes: 0

Related Questions