Поскольку вы используете PDO
, имеет смысл использовать некоторые его сильные стороны - в первую очередь в этом случае prepared statements
и bound parameters
, чтобы сделать SQL намного безопаснее от злоумышленников.
Если вы отделяете соединение с базой данных от оставшегося кода, у вас есть соединение с базой данных, которое можно быстро и легко использовать в другом месте, просто включив его во время выполнения, поэтому первым фрагментом кода ниже может быть файл соединения db.
(я вижу, что вы сами решили проблему перед публикацией этого сообщения ...)
<?php
/*******************
dbo-conn.php
*/
try{
$options=array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_general_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);
$dbuser='root';
$dbpwd='';
$bdd=new PDO( 'mysql:host=localhost;dbname=test1;port=3306;charset=UTF8', $dbuser, $dbpwd, $options );
}catch( PDOException $e ){
exit( $e->getMessage() );
}
?>
On the page that does the database inserts
<?php
try{
# test that the variable is set and available...
if( !empty( $_GET['temp1'] ) ){
# rudimentary check for number
if( !is_numeric( $_GET['temp1'] ) )throw new Exception( sprintf( 'Supplied parameter "%s" does not appear to be a number', $_GET['temp1'] ) );
$valeur = $_GET['temp1'];
# include the db connection
# the path used here depends where the file `dbo-conn.php` is saved
# - this assumes the same directory
require 'dbo-conn.php';
# generate sql & prepared statement
$sql='insert into `temp` ( `valeur` ) values ( :valeur )';
$stmt = $bdd->prepare( $sql );
# check the prepared statement was created ok before attempting to execute it
if( !$stmt ) throw new Exception( 'Failed to prepare sql "INSERT" query'
# bind the placeholder to the supplied user input
$stmt->bindParam( ':valeur', $valeur, PDO::PARAM_STR );
# commit the query
$result = $stmt->execute();
if( !$result )throw new Exception( 'oops! something went wrong' );
# display a message to the user
printf('donnee %s ecrite!', $valeur );
}
}catch( Exception $e ){
exit( sprintf( 'Erreur: %s', $e->getMessage() ) );
}
?>