Prajwal K M Prajwal K M - 5 months ago 16
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.

<?php
session_start();
define('HOST','localhost');
define('USER','miiskyroot');
define('PASS','miisky@123');
define('DB','miisky123');

$response = array();

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

if(!mysqli_connect_errno()){

$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())";

if(mysqli_query($con,$sql)){

echo "Successfully Saved";

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

}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>


this is my contact list in database

Answer

You can simply use REPLACE() :

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

Or if you want to change it in the database :

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