Ujang Hardman
Ujang Hardman

Reputation: 115

How to substring WHERE in SELECT php mysql

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.

Upvotes: 0

Views: 2347

Answers (3)

ajit
ajit

Reputation: 86

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";

Upvotes: 2

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

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)

Upvotes: 3

Soorajlal K G
Soorajlal K G

Reputation: 786

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";

Upvotes: 2

Related Questions