简体   繁体   中英

SELECT COUNT * SQL PHP doesn't work

I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(

SOLVED : THIS IS THE WORKING CODE :

<?php session_start(); ?>
<?php  

if($_POST['code-postal'] === '') { 
        $hasError = true;
} else {
        $variable = $_POST['code-postal'];
        $code = intval($variable);
}

    mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());   

mysql_select_db('xxxxxxxxxx');  

$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'"; 
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error()); 

$data = mysql_fetch_assoc($req);

if($data['total_count'] == 1) {
    $verif = true;
}
else {
    $verif = false;
}
// on ferme la connexion à mysql 
mysql_close();  
?> 
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'"; 
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error()); 

$data = mysql_fetch_assoc($req);

if($data['total_count'] == 1) {
    $verif = true;
}
else {
    $verif = false;
}

Here is the working code.

mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.

I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM