April 16, 2012

Weird behavior PHP vs MySQL

Question by silentw

This is the SQL:

TRUNCATE TABLE `dc_path`;
INSERT INTO dc_path (coords) VALUES('(40.64406436923055, -8.638539251709062)');
INSERT INTO dc_path (coords) VALUES('(40.62791121610622, -8.615193304443437)');
INSERT INTO dc_path (coords) VALUES('(40.62895347295352, -8.6625718444825)');

If I try to execute that query on phpmyadmin it works just fine, but through php it gives me this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO dc_path (coords) VALUES('(40.64406436923055, -8.638539251709062)');I' at line 1

I tried many things and I can’t work it out!

Thanks in advance.

Edit:

PHP

function insertPath($coords){
    $conn = connectDB();
    $coords = explode(";",$coords);
    $sql = "";

    $sql = "TRUNCATE TABLE `dc_path`; ";

    for($i=0;$i<count($coords)-1;$i++){
        $sql .= "INSERT INTO dc_path (coords) VALUES('".$coords[$i]."');";
    }
    echo $sql;
    $query = mysql_query($sql, $conn) or die(mysql_error());

    closeDB($conn);
    return true;
}

the $coords variable contains something like these values:

(40.638854101691635, -8.6515855163575);(40.629474595277166, -8.63235944213875);

Answer by TomUnite

function insertPath($coords){
    $conn = connectDB();
    $coords = explode(";",$coords);

    mysql_query("TRUNCATE TABLE `dc_path`", $conn);

    for($i=0;$i<count($coords)-1;$i++){
        mysql_query("INSERT INTO dc_path (coords) VALUES('".$coords[$i]."')", $conn);
    }

    closeDB($conn);
    return true;
}

Answer by Starx

You cannot query more than one statement using mysql_query().

Query like this

for($i=0;$i<count($coords)-1;$i++){
    $sql = "INSERT INTO dc_path (coords) VALUES('".$coords[$i]."');";
    $query = mysql_query($sql, $conn) or die(mysql_error());
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!