I have the following code
$name = 'myname';
$mail = 'my#mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();
I want print the query
"INSERT INTO `agenz` (`name`, `email`) VALUES ('myname','my#mail.it')"
for creating a log.So how to do that?
thanx.
Try fullQuery like below:
$name = 'myname';
$mail = 'my#mail.it';
$qwt = "INSERT INTO `agenz` (`name`, `email`) VALUES (?,?)";
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $name, $mail);
$result->execute();
echo $result->fullQuery;
or
$result->debugQuery();
var_dump($result->debugBindedVariables());
if you want to get the error
var_dump($result->errno);
I have solved!
$qwt = "INSERT INTO `age` (`name`,`email`) VALUES (?,?)";
$par = array($name, $mail);
$result = $connessione->prepare($qwt);
$result->bind_param('ss', $par[0], $par[1]);
$result->execute();
echo "contenuto: " .SqlDebug($qwt, $par);
function SqlDebug($raw_sql, $params=array())
{
$keys = array();
$values = $params;
foreach ($params as $key => $value)
{
// check if named parameters (':param') or anonymous parameters ('?') are used
if (is_string($key)) { $keys[] = '/:'.$key.'/'; }
else { $keys[] = '/[?]/'; }
// bring parameter into human-readable format
if (is_string($value)) { $values[$key] = "'" . $value . "'"; }
elseif (is_array($value)) { $values[$key] = implode(',', $value); }
elseif (is_null($value)) { $values[$key] = 'NULL'; }
}
$raw_sql = preg_replace($keys, $values, $raw_sql, 1, $count);
return $raw_sql;
}
You can use variable directly in the statement like following
$name="ABC";
$mail="me#someone.com";
$value= "I am $name mail id $mail";
Related
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.
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;
}
}
}
You need to escape the string parameters. And it is much better if you can use PDO extension, because prepared statements can take care of escaping for you and also helps with preventing SQL injection and some other security concerns.
function insertData(PDO $dbh, $csvfile) {
$x = 0;
foreach ($csvfile as $data)
{
$query = "INSERT INTO users (email, name, surname) VALUES (?, ?, ?)";
$params = [
$csvfile[$x]['email'],
$csvfile[$x]['name'],
$csvfile[$x]['surname']
];
$statement = $pdo->prepare($query);
$statement->execute();
$x++;
}
}
PDO::prepare
PDOStatement::execute
Solution using prepared query
function insertData($dbname, $tbname, $csvfile)
{
$result = [];
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=$dbname");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'INSERT INTO $1 (email, name, surname) VALUES ($2, $3, $4)');
// Execute the prepared query. Note that it is not necessary to escape
foreach ($csvfile as $data)
{
$email = $data['email'];
$name = $data['name'];
$surname = $data['surname'];
$query = "";
$result[] = pg_execute($dbconn, "my_query", array($tbname, $email, $name, $surname));
}
if (in_array(false, $result) )
return false;
else
return true;
}
$dbname = "your dbname";
$tbname = "name of table";
$csvFile = [];
if (insertData($dbname, $tbname, $csvFile))
echo "Data inserted";
else
echo "Data not inserted";
So i took note of the suggestions from #Karsten Koop and #TOH19, and came up with this code which is working;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = pg_escape_string($csvfile[$x]['email']);
$name = pg_escape_string($csvfile[$x]['name']);
$surname = pg_escape_string($csvfile[$x]['surname']);
$query = "INSERT INTO users (email, name, surname) VALUES ('".$email."', '".$name."', '".$surname."')";
$result = pg_query($pg, $query);
$x++;
}
}
i am basicly trying to update user information with a dynamic query.Everything good but when i try to execute query its return always false.
function updateUser($username, $email, $pass){
$arr = [];
$values = [];
$params = [];
if(isset($username))
{
array_push($arr, "userName = :username");
array_push($values, $username);
array_push($params, ":username");
}
if(isset($email))
{
array_push($arr, "userEmail = :email");
array_push($values, $email);
array_push($params, ":email");
}
if(isset($pass))
{
array_push($arr, "userPassword = :pass");
array_push($values, $pass);
array_push($params, ":pass");
}
$sql = "UPDATE users SET " . implode(", ", $arr) . " WHERE userId = :uId";
$query = $db->prepare($sql);
foreach ($params as $key) {
foreach ($values as $value) {
$query->bindValue($key, $value, PDO::PARAM_STR);
}
}
$query->bindValue(":uId", $_SESSION["userId"]);
if($query->execute() && $query->rowCount() > 0)
return true;
else
return false // always false return
}
this is my array datas:
this is funny. i can't answer my question.
i found the solution. it is because of double foreach loop.
$i = 0;
foreach ($params as $key) {
$query->bindValue($key, $values[$i], PDO::PARAM_STR);
$i++;}
function insert_data($data, $table, $action )
{
include "connect.php";
$columnnvalues = json_decode(json_encode($data), true);
$columns = array ();
$values = array();
foreach($columnnvalues as $key=>$col)
{
foreach($col as $keyval=>$val)
{
array_push($columns, $col);
array_push($values, $val);
}
}
$sql = "INSERT INTO " .$table. " (" .implode(", ", $columns).") VALUES (".implode(", ", $values). ")";
echo $sql;
$stmt = mysqli_prepare($con,$sql);
if($stmt)
{
mysqli_stmt_execute($stmt);
$result["success"] = true;
}
else
{
$result["success"] = false;
$result["error"] = 1;
}
echo json_encode($result);
}
sample datas
$datas = Array ("name"=>"sample", "permanentaddress"=>"add", "contact"=>"aaaa", "status"=>"Active");
insert_data($datas, "customers", "add" )
I am attempting to bind params to a sql statement using call_user_func_array as describe on Dynamically Bind Params in Prepared Statements with MySQLi; however, my mysqli_prepare keeps returning false.
Here is my data function that is called to store data:
function storeData($form_data, $table_name, $cxn){
if(!is_array($form_data)){
return false;
exit();
}
$types = str_repeat("s", count($form_data));
$params = array();
$params[] = &$types;
$keys = array_keys($form_data);
$values = array_values($form_data);
for ($i = 0; $i < count($values); $i++) {
$params[] = &$values[$i];
}
$sql = "INSERT INTO $table_name (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")
ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
if($stmt = mysqli_prepare($cxn, $sql)){
call_user_func_array(array($stmt, 'bind_param'), $params);
return mysqli_stmt_execute($stmt);
}
Here is my $sql string at time of prepare:
$sql"INSERT INTO interest (Baseball,Basketball,Camping,Canoeing,Cycling,Football,Gaming,Golf,Hiking,Parks,Photography,Runway,Skydiving,Soccer,Username) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE Baseball = VALUES(Baseball),Basketball = VALUES(Basketball),Camping = VALUES(Camping),Canoeing = VALUES(Canoeing),Cycling = VALUES(Cycling),Football = VALUES(Football),Gaming = VALUES(Gaming),Golf = VALUES(Golf),Hiking = VALUES(Hiking),Parks = VALUES(Parks),Photography = VALUES(Photography),Runway = VALUES(Runway),Skydiving = VALUES(Skydiving),Soccer = VALUES(Soccer),Username = VALUES(Username)"
Here is my $params and $key outputs:
$keysarray[15]
$keys[0]"Baseball"
$keys[1]"Basketball"
$keys[2]"Camping"
$keys[3]"Canoeing"
$keys[4]"Cycling"
$keys[5]"Football"
$keys[6]"Gaming"
$keys[7]"Golf"
$keys[8]"Hiking"
$keys[9]"Parks"
$keys[10]"Photography"
$keys[11]"Runway"
$keys[12]"Skydiving"
$keys[13]"Soccer"
$keys[14]"Username"
$paramsarray[16]
$params[0]"sssssssssssssss"
$params[1]"0"
$params[2]"0"
$params[3]"0"
$params[4]"0"
$params[5]"0"
$params[6]"0"
$params[7]"0"
$params[8]"0"
$params[9]"0"
$params[10]"0"
$params[11]"0"
$params[12]"0"
$params[13]"0"
$params[14]"0"
$params[15]"test0613"
$valuesarray[15]
$values[0]"0"
$values[1]"0"
$values[2]"0"
$values[3]"0"
$values[4]"0"
$values[5]"0"
$values[6]"0"
$values[7]"0"
$values[8]"0"
$values[9]"0"
$values[10]"0"
$values[11]"0"
$values[12]"0"
$values[13]"0"
$values[14]"test0613"
There error existed in a column i was attempting to map which did not exist. The error procedure was found here, which allowed me to produce fatal errors that noted a column did not exist in the table I was referencing.
Currently I'm stuck on how to add the values of my array into a variable, to output in a query.
Here are my data stored in:
try {
$link->create(array(
'uid' => $user->data()->id,
'name' => Input::get('name'),
'hyperlink' => Input::get('hyperlink')
));
} catch (Exception $e) {
die($e->getMessage());
}
And with this function I'm trying to get the values from that array into 1 variable:
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$x = 1;
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
But when I echo the sql it only gives the last value of the array. What am I doing wrong?
Thanks!
You could try something like this, cuts down on the looping a bit, and could be combined into a single line actually... EDIT: neglected to quote the values... updated appropriately
if (count($fields)) {
$field_list = implode(", ", array_keys($fields));
$value_list = implode("', '", array_values($fields));
$sql = "insert into `$table` ($field_list) values('$value_list')";
}
Here is another option and I couldn't figure out what was wrong with your script, it looks correct but wasn't able to find the problem. I always use this class method when inserting db values dynamically.
function insertRecord ($fieldarray)
{
$this->errors = array();
//Connect to the DB for table insert
global $dbconnect, $query;
$dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);
//Now, using the contents of $fieldlist which was set in the class constructor we can edit the input array to filter out any items which do not belong in this database table. This removes the SUBMIT button, for example.
$fieldlist = $this->fieldlist;
foreach ($fieldarray as $field => $fieldvalue) {
if (!in_array($field, $fieldlist)) {
unset ($fieldarray[$field]);
} // if
} // foreach
//Now construct the query string to insert a new
//record into the database:
$query = "INSERT INTO $this->tablename SET ";
foreach ($fieldarray as $item => $value) {
$query .= "$item='$value', ";
} // foreach
//You may have noticed that each 'name=value' pair was appended
//to the query string with a trailing comma as a separator,
//so we must remove the final comma like so:
$query = rtrim($query, ', ');
//Now execute the query. Notice here that instead of the default
//error checking I look specifically for a 'duplicate key' error
//and return a simple error message rather terminating the whole
//script with a fatal error.
$result = #mysql_query($query, $dbconnect);
if (mysql_errno() <> 0) {
if (mysql_errno() == 1062) {
$this->errors[] = "A record already exists with this ID.";
} else {
trigger_error("SQL", E_USER_ERROR);
} // if
} // if
//Last act is to return control to the calling script.
return;
} // insertRecord
IMHO the function above has the necessary checks for an insert statement and error handling which I found useful.
I think you can use the function array_values like you use the function array_keys to do this easier.
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$values = array_values($fields); // why another logic for the same result.. ?
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES (`" . implode('`, `', $values) . "`)";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
The problem is the $values = $values is inside the foreach loop.
foreach ($fields as $field => $values) {
// The problem is right here, each time this loops, you are
// setting the entire $values variable to be just the current iteration
// of the $fields variable.
$values = $values;
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
Try this instead:
$sql_values = '';
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$sql_values.= $values.', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ($sql_values)";