对于MySQL中的空值设置为零

时间:2016-03-17 12:14:44

标签: php mysql

我尝试将空MySQL值设置为零。我使用了IFNULL,但它不起作用。对不起,我的英语不好。

<select name="stock_i_h_id" id="stock_i_h_id" class="form-control  m-bot15" required>
<option value="" selected="selected">--Select Item --</option>
<?php 
$ids=array();
$qry = mysql_query("SELECT IFNULL(stock_i_h_id,0) FROM other_stock_item_creation where userId='".$_SESSION['userId']."' and status_my='0'");
while($row_sid =  mysql_fetch_assoc($qry)){
    $ids[]=$row_sid["stock_i_h_id"]; 
}
$st = implode(",",$ids);                    
$ids2=array();
$qry2 = mysql_query("SELECT IFNULL(stock_i_h_id,0) FROM dpr_stock_item where userId='".$_SESSION['userId']."' and status_my='0'");
while($row_sid2 =  mysql_fetch_assoc($qry2)){
    $ids2[]=$row_sid2["stock_i_h_id"]; 
}
$st2 = implode(",",$ids2);

$stock_item_head_name = mysql_query("select * from stock_item_head_name where userId='".$_SESSION['userId']."' and status_my='0' and id not in (".$st.",".$st2.") order by id ASC"); 
$current_date= date('d-m-Y');
while($rows_stock_item_head_name = mysql_fetch_assoc($stock_item_head_name)) 
{
?>
<option value="<?php echo $rows_stock_item_head_name['id'] ?>"><?php echo $rows_stock_item_head_name['stock_item_name'] ?></option required>
<?php 
}
?>

如果$qry$qry2返回空值,则$ st和$ st2都变为空,然后在第三个查询中NOT IN('','')而不是NOT IN(0,0) {{1} }})

编辑: 当表$stock_item_head_nameIFNULL都有条目时,我的代码在没有other_stock_item_creation的情况下正常工作。但是当表格为空时,它无法使用dpr_stock_itemIFNULL

3 个答案:

答案 0 :(得分:0)

如果值为NULL,则IFNULL肯定会有效。您的列必须具有不同的值。如果是字符串,则可能有效:

SELECT IF(stock_i_h_id = '', 0, stock_i_hd) ...

答案 1 :(得分:0)

喜欢

SELECT if(stock_i_h_id is null,0,stock_i_h_id ) as stock_i_h_id 

如果stock_i_h_id为null,则返回零,否则为stock_i_h_id

的值

答案 2 :(得分:0)

什么是列stock_i_h_id列的类型?使它默认为空!

ALTER TABLE `other_stock_item_creation` change `stock_i_h_id` `stock_i_h_id` int(10) unsigned DEFAULT NULL;

比(如果stock_i_h_id DEFAULT NULL):

UPDATE `other_stock_item_creation` set `stock_i_h_id`=NULL WHERE stock_i_h_id='';

试试你的代码。