Prajwal K M Prajwal K M - 1 year ago 48
PHP Question

How to trim first three characters based on the first letter(expression) before inserting into the database

my php file

This is my code to retrieve data from database.

Here i need to remove first three characters based on the first expression(+) and followed by two numbers i.e(91). So totally i need to remove phone numbers which have +91 in database.
Can anyone help me regarding this.


$response = array();

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');


$error_flag = false;

$contacts = json_decode($_POST['contacts'], true);
foreach($contacts as $contact){

//$trimmed = $contact['phone'];

//$title = str_replace("+91", "", trim($trimmed));
// $prefix = '+91';
// $str = $contact['phone'];
// if (substr($str, 0, strlen($prefix)) == $prefix)
// { echo $str = substr($str, strlen($prefix)); }

$sql = "INSERT INTO contacts (vault_no , name, phone, created_at)
VALUES ('".$contact['vault_no']."', '".$contact['name']."', REPLACE('".$contact['phone']."','+91',''), NOW())";


echo "Successfully Saved";

$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);

$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);

this is my contact list in database

Answer Source

You can simply use REPLACE() :

SELECT REPLACE(,'+91','') as mobile
FROM YourTable t

Or if you want to change it in the database :

UPDATE YourTable t
SET = REPLACE(,'+91','')