我有一个函数disp,我传递一个表的列名值来检查数据库中该列值是1还是0。如果值为1则应返回1否则为0这是我试图制作的函数。但没有给出理想的结果。
请告诉我是否有其他方法来检查特定行的列的值是1还是0
function disp($x){
@$ncenter=$_SESSION['ncenter'];
$sql = "SELECT COUNT('$x') FROM sel WHERE 'numcenter' = '$ncenter' and '$x' = 1";
$sql.=';';
echo $sql;
$res = mysql_query($sql);
if(!$res) die ('Unable to run query:'.mysql_error());
$row = mysql_fetch_array($res);
if($row["COUNT('$x')"] > 0){
return 0;
}
else{
return 1;
}
}
提前谢谢
答案 0 :(得分:0)
// SELECT * FROM sel WHERE 'numcenter' = '$ncenter' and '$x' = 1 LIMIT 1
if(empty($row)){
return 0;
}
else{
return 1;
}
答案 1 :(得分:0)
您可以使用SQL CASE语句:
SELECT (CASE WHEN `column_name` = '1' THEN 1 ELSE 0 END) AS `column_name_equals_one` FROM `table_name` WHERE `row_identifier_column_name` = 'row_identifier_value';
编辑:我也重写了你的代码,因为它伤害了我的眼睛(我没有测试过这个)。
/**
* Checks if the value of a specific field equals 1 or 0
*
* @param string $columnName The name of the column
* @param string $rowIdentifier The row identifier
* @returns boolean|integer Returns false on failure or the query result as an integer on success
*/
function disp($columnName, $rowIdentifier) {
$returnValue = false;
$query = sprintf("SELECT (CASE WHEN `%s` = '1' THEN 1 ELSE 0 END) AS `result` FROM `table_name` WHERE `row_identifier_column_name` = '%s'", mysql_real_escape_string($columnName), mysql_real_escape_string($rowIdentifier));
if (($result = mysql_query($query)) !== false) {
if (($row = mysql_fetch_assoc($result)) !== false) {
$returnValue = (int)$row['result']
}
mysql_free_result($result);
}
return $returnValue;
}
答案 2 :(得分:0)
试试这个;
$row = mysql_result($res, 0, 0);
$numb_of_rows = mysql_num_rows($row);
if($numb_of_rows > 0){
return 1;
}
else{
return 0;
}