0

How to check database with php variables like this ?

I have

$check = "1234567890";

This is table : check_data

 _________ ______________________________________________________________
|   id    |                         key_pass                             |
|_________|______________________________________________________________|
|____1____|_______________1234567890abcdefghij___________________________|
|____2____|_______________6545ryu76543werfdt54___________________________|
|____3____|_______________345jfuryt75yrhtufkgo___________________________|
|____4____|_______________weoiufoiweu9ew8ew8w8___________________________|
|____5____|_______________oi34ioruiofuefiusdfo___________________________|
|____6____|_______________iuyiuysdifuysfiuyfds___________________________|

i want to check like this.

$sql = "SELECT * FROM check_data WHERE key_pass(first char to ten char) = '$check'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
if($result)
  {echo "found";}
else
  {echo "not found";}

How can i do that ?

1
  • Note that PHP's mysql_ API is deprecated. Commented Jul 21, 2014 at 9:48

7 Answers 7

5

Check MySQL manual, you're looking for SUBSTRING function.

$sql = "SELECT * FROM check_data WHERE SUBSTRING(key_pass, 1, 10) = '" . mysql_real_escape_string($check) . "';
Sign up to request clarification or add additional context in comments.

Comments

4

Try with LEFT

LEFT(key_pass , 10);

Like

$sql = "SELECT * FROM check_data WHERE LEFT(key_pass , 10) = '$check'";

Also you can use SUBSTRING like

$sql = "SELECT * FROM check_data WHERE SUBSTRING(key_pass ,1, 10) = '$check'";

1 Comment

Substring starts from 1. Source: w3resource.com/mysql/string-functions/…
2

the function you need is LIKE,

$sql =  "SELECT * FROM check_data WHERE key_pass like ('$check%')";

you could also do

$sql =  "SELECT * FROM check_data WHERE SUBSTR(key_pass,1,10) = '$check%'";

Comments

1

You can use a LEFT() function like this:

ql = "SELECT * FROM check_data WHERE left(key_pass,10) = '$check'";

There are a whole family of string functions that can be useful. Check the MySQL reference

Comments

0
$sql = "SELECT * FROM check_data WHERE SUBSTRING(key_pass, 1, 10)= '$check'";

Comments

0
$sql = "SELECT * FROM check_data WHERE key_pass LIKE  % $check %";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
if($result)
  {echo "found";}
else
  {echo "not found";}

1 Comment

Change % $check %"; to $check %";
0

Try this

    "SELECT * FROM check_data WHERE SUBSTR(key_pass,1,10) = ".$check

or

    "SELECT * FROM check_data WHERE key_pass LIKE '".$check."%'"

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.