Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

php - 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();


    $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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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','')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...