Search code examples
phpmysqlconcatenationstring-concatenation

concat php value with entire quotes in sql query


How to concat this php value with entire quotes in sql query, so that it saves as properly in phpmyadmin database?

 $db = new mysqli('localhost','root','','geo'); 

// Each value is a placeholder

$sql = "UPDATE file_contents SET Origin_URL = CONCAT('https://www.google.com/maps/dir/', ?, ',' ?, '/', ?, ',', ?) WHERE Sl = 1 LIMIT 6";

$stmt = $db ->prepare($sql);

// First parameter should correspond to number and types of your arguments
// You have 5, first four are strings, fifth is a number, so "ssssd"

$stmt->bind_param($OriginLatId,$OriginLongId,$DestinationLatId,$DestinationLongId);

$stmt->execute();

Please help me get the correct sql query to insert this url in my database successfully, this is the table, and I have made the Origin_URL column into a varchar column. The data goes into this column.

This is table, and I have made the Origin_URL column into a varchar column. The data goes into this column.


Solution

  • There are a number of issues with your string concatenation, + is for addition, variables in single quotes are strings, not variables, and you seem to be adding quotes in too many instances.

    You should be able to build your string with the complex curly braces in double quotes:

    $val1 = "https://www.google.com/maps/dir/{$OriginLatId},{$OriginLongId}/{$DestinationLatId},{$DestinationLongId}";
    

    You can read more about this here, http://php.net/manual/en/language.types.string.php.

    or by standard concatenation:

    $val1 = 'https://www.google.com/maps/dir/' .  $OriginLatId .',' . $OriginLongId . '/' . $DestinationLatId . ',' . $DestinationLongId;
    

    You can read more about this here, http://php.net/manual/en/language.operators.string.php.

    Then just write that to the DB. There's no need for the mysql concat function.

    $sql = 'UPDATE file_contents 
    SET Origin_URL = ? 
    WHERE Sl = 1 LIMIT 6';
    $stmt = $db->prepare($sql);
    $stmt->bind_param('s', $val1);
    $stmt->execute();