Jump to content

[SOLVED] substr($num) Advice


phpnewbie112

Recommended Posts

Hello,

 

I really need your advices and ideas about the given problem.

 

I have a field in a form dedicated to enter international format mobile numbers example 1928123456, 336123456789, 4156897526, 2010102030

 

I have a mysql tables with 3 fields:

Country - Code - Rate

 

example:

France - 336 - 5

USA - 1 - 4

 

How can I make the following code work but while reading the values from the db rather than a manual one:

 

if(substr($num,0,3)=="336") {

    $rate = "5";

}

 

else

if(substr($num,0,1)=="1") {

    $rate = "4";

}

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/129802-solved-substrnum-advice/
Share on other sites

try this:

 

<?php
  $number = '1928123456';
  $sql = sprintf("SELECT * FROM rates WHERE SUBSTRING('%s',0,LENGTH(code)) = code",mysql_real_escape_string($number));
  $result = mysql_query($sql) or die(mysql_error());
  while($row = mysql_fetch_assoc($result)){
    print_r($row);
  }
?>

oops...1 not 0:

 

<?php
  $number = '1928123456';
  $sql = sprintf("SELECT * FROM rates WHERE SUBSTRING('%s',1,LENGTH(code)) = code",mysql_real_escape_string($number));
  $result = mysql_query($sql) or die(mysql_error());
  while($row = mysql_fetch_assoc($result)){
    print_r($row);
  }
?>

<?php
  $number = '1928123456';
  $sql = sprintf("SELECT * FROM rates WHERE SUBSTRING('%s',1,LENGTH(code)) = code",mysql_real_escape_string($number));
  $result = mysql_query($sql) or die(mysql_error());
  while($row = mysql_fetch_assoc($result)){
    print $row['rate'];
  }
?>

One more question if you don't mind, I tried to include the following:

 

  if isempty($row['rate']) {

      echo "Not Included";

  }

 

so when there is no return rate, it gives "not included" message but it is return nothing. pls advice. thanks a million

<?php
  $number = '1928123456';
  $sql = sprintf("SELECT * FROM rates WHERE SUBSTRING('%s',1,LENGTH(code)) = code",mysql_real_escape_string($number));
  $result = mysql_query($sql) or die(mysql_error());
  if(mysql_num_rows($result)){
    while($row = mysql_fetch_assoc($result)){
      print $row['rate'];
    }
  }else{
    print "Not included";
  }
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.