0

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.

7
  • Try $queryalat1="select * from tb_master where kd_barang2 = '".substr($data1['kd_barang2'],0,7)."' && jenis_barang = 'alat habis pakai' Group by merk_barang"; Commented Apr 14, 2015 at 9:07
  • 1
    NEVER concatenate strings into SQL queries! Learn how to use parameters. Commented Apr 14, 2015 at 9:08
  • Is the ID field numeric or textual? If the ID field is numeric, substring will return nothing. Commented Apr 14, 2015 at 9:11
  • not true, php will happily substr a number and give the desired result: echo substr(12345678, 1, 5) == 23456 Commented Apr 14, 2015 at 9:12
  • 1
    @pala_ And he's using also MySQL's SUBSTRING, if you read the actual query. Actually the problem is with base: PHP is zero-based, MySQL one-based, so my comment was wrong. Commented Apr 14, 2015 at 9:16

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

ohh i see, your solution really work.. :D I didn't know mysql's substring start from 1... -_- Thank you so much, guess i have to learn more...
2

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

1 Comment

It should be LEFT(kd_barang2, 7)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.