douliang6563
douliang6563
2015-04-14 09:01

如何在SELECT php mysql中子字符串WHERE

已采纳

I have a column kd_barang2 as an id in my table. The values is like this: 010000101.

I want to select the first 7 number (0100001) and then show it.

The script to select is like this:

$queryalat1="select * from tb_master
  where kd_barang2 = '".$data1['kd_barang2']."'
  && jenis_barang='alat habis pakai'
  Group by merk_barang";

and then I tried this kind of code

$queryalat1="select * from tb_master
  where SUBSTRING(kd_barang2,0,7) = '".substr($data1['kd_barang2'],0,7)."'
  && jenis_barang='alat habis pakai'
  Group by merk_barang";

but it failed, because it didn't show any data in my table.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dsbezji539113152 dsbezji539113152 6年前

    You're using MySQL's SUBSTRING function with the wrong start value. In PHP substr() will start with zero, but in MySQL it starts with 1. So you need to use SUBSTRING(kd_barang2, 1, 7)

    点赞 评论 复制链接分享
  • dongwen2794 dongwen2794 6年前

    Try this..
    $queryalat1="select * from tb_master
    where left(kd_barang2,7) = '".substr($data1['kd_barang2'],0,7)."'
    && jenis_barang='alat habis pakai'
    Group by merk_barang";

    点赞 评论 复制链接分享
  • douzun4443 douzun4443 6年前

    Try

    $queryalat1="select * from tb_master where LEFT(kd_barang2,8) = '".substr($data1['kd_barang2'],0,7)."' && jenis_barang='alat habis pakai' Group by merk_barang";
    
    点赞 评论 复制链接分享