So it’s probably a really stupid/basic question, but i have this simple PHP function (which works) and inserts data into a PostgreSQL DB.
My issue is when it encounters specific data;
function insertData($pg, $csvfile) { $x = 0; foreach ($csvfile as $data) { $email = $csvfile[$x]['email']; $name = $csvfile[$x]['name']; $surname = $csvfile[$x]['surname']; $query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')"; $result = pg_query($pg, $query); $x++; } }
And while this works, it falls over with a surname such as:
O’hare
And obviously this occurs because then the PHP code comes out as:
…VALUES (‘john@example.com’, ‘John’, ‘O’hare’)”;
but im not sure of how i should be structuring the PHP to allow for this.
Advertisement
Answer
Try this:
function insertData($pg, $csvfile) { $nbr = count(file($csvfile)); for($i=0; $i<$nbr; $i++) { $email = pg_escape_string( $csvfile[$i]['email'] ); $name = pg_escape_string( $csvfile[$i]['name'] ); $surname = pg_escape_string( $csvfile[$i]['surname'] ); $query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')"; $result = pg_query($pg, $query); if (!$result) { echo "Error while executing the query: " . $query; exit; } } }