PUT and POST query string pattern - php

i am working on my own restfull api. I have read many article about, but i come out more confused that before.
fist question:
in PUT request is correct to use question mark (?) ex:
http://myapi.me/testApi/v5/create/places?address=Five&building=old
or i must to use
http://myapi.me/testApi/v5/create/places/address=Five&building=old
if the second is the correct way, how i can explode the query string for create my insert statement? my code work well with (?). But curl command does not want to enter the record. So i need to modify the script to reflect the correct way with(/) instead of (?).
Please help...
my code:
$body = file_get_contents("php://input");
$content_type = false;
if(isset($_SERVER['CONTENT_TYPE'])) {
$content_type = $_SERVER['CONTENT_TYPE'];
// echo $content_type;
}
switch($content_type) {
//other case...
case "application/x-www-form-urlencoded":
parse_str($body, $postvars);
foreach($postvars as $field => $value) {
$parameters[$field] = $value;
}
$this->format = "html";
break;
default:
// we could parse other supported formats here
break;
}
$this->parameters = $parameters;
private function createRecord(){
if($this->get_request_method() != "PUT"){
$this->response('',406);
}
$table = strtolower(trim(str_replace("/", "", $_REQUEST['rquest'])));
/*
$Q = explode("/", $_SERVER["rquest"]);
print_r(array_values($Q));
echo "\n";
*/
$uri = $this->parameters;
if($uri){
array_shift($uri);
foreach( $uri as $k => $v )
{
$aKeyPholder[]= $k;
$aKey[]= ':'.$k;
}
$aKeyPholder= implode(',', $aKeyPholder);
$aKey= implode(',', $aKey);
$insert = "INSERT INTO '$table' ($aKeyPholder) VALUES ($aKey)";
// echo "insert=$insert\n";
$stmt = $this->db->prepare($insert);
foreach($uri as $k => &$v){
$stmt->bindParam(':'.$k, $v, PDO::PARAM_STR);
}
//$stmt->execute();
if ($stmt->execute()) { echo "Record succesfully created!";}
$this->response($this->json($success),200);
}
else{
$this->response('',204); // If no records "No Content" status
}
}

Related

Insert in database with wpdb in PHP

I try to make a function to insert more fields in database.
I find an example, but maybe more parameters is deprecated...or i have an error.
Here is my code:
private function _setUserPersonalDetails($blog_id, $personal_data, $operation = 'insert') {
global $wpdb;
// Strip any html tags from the about and address fields.
$tmp = array();
foreach ($personal_data as $key => $val) {
if (($key === 'about') || ($key === 'address')) {
$tmp[$key] = strip_tags($val);
}
else {
$tmp[$key] = $val;
}
}
$personal_data = $tmp;
if ($operation == 'insert') {
// Save personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('INSERT INTO wp0_users_conta_data (blog_id, type, data) VALUES (%d, %s, %s)', $blog_id, $type, $encoded_data);
$wpdb->query($q);
}
if ($operation == 'update') {
// Update personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('UPDATE wp0_users_conta_data set data=%s where blog_id=%d and type=%s', $encoded_data, $blog_id, $type);
$wpdb->query($q);
}
}
}
I spent more one week to solve the problem, but i don't find any solutions. I appreciate any helps. Thank you!

PDO not inserting - error code 00000

I have an issue with my INSERT query, $pdo->execute return false, with error code 00000
Query
string 'INSERT INTO module_test (img_name, description, priority) VALUES(:img_name, :description, :priority)' (length=100)
errorInfo() return:
array (size=3)
0 => string '00000' (length=5)
1 => null
2 => null
Code:
private function Init($query, $parameters = "")
{
# Connect to database
if (!$this->bConnected) {
$this->Connect();
}
try {
# Prepare query
$this->sQuery = $this->pdo->prepare($query);
# Add parameters to the parameter array
$this->bindMore($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param => $value) {
$type = PDO::PARAM_STR;
switch ($value[1]) {
case is_int($value[1]):
$type = PDO::PARAM_INT;
break;
case is_bool($value[1]):
$type = PDO::PARAM_BOOL;
break;
case is_null($value[1]):
$type = PDO::PARAM_NULL;
break;
}
// Add type when binding the values to the column
$this->sQuery->bindValue($value[0], $value[1], $type);
}
}
# Execute SQL
var_dump($query);
var_dump($this->sQuery->execute());
var_dump($this->sQuery->errorInfo());
}
catch (PDOException $e) {
# Write into log and display Exception
echo $this->ExceptionLog($e->getMessage(), $query);
die();
}
# Reset the parameters
$this->parameters = array();
}
public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$query = trim(str_replace("\r", " ", $query));
$this->Init($query, $params);
$rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query));
# Which SQL statement is used
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->sQuery->rowCount();
} else {
return NULL;
}
}
public function insert($table, $keyValue)
{
$fieldString = '';
$valueString = '';
$i = 1;
foreach ($keyValue as $key => $currKeyValue)
{
$fieldString .= $key;
$valueString .= ':'.$key;
if($i != count($keyValue))
{
$fieldString .= ', ';
$valueString .= ', ';
}
$i++;
}
$query = 'INSERT INTO '.$table.' ('.$fieldString.') VALUES('.$valueString.')';
$this->query($query, $keyValue);
}
Parameters array
F:\Dev\wamp\wamp64\www\include\class\Database.class.php:216:
array (size=3)
'img_name' => string 'ttt1' (length=4)
'description' => string 'ttt1' (length=4)
'priority' => int 0
I already try this query in phpmyadmin and everything worked well.
If someone know how to solve this?
thanks
PS: sorry for my bad english
PDO is reported not to fill the errorInfo property in certain circumstances.
Instead, you have to make it throw an exception, which is the most reliable way to get the error message. To do so, in your constructor, add this line
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Also note that your class is a genuine example of all the mistakes one could make writing a PDO wrapper. I compiled the most popular mistakes in an article, Your first database wrapper's childhood diseases and your class contains every single one of them.

php - contao - saving my model leaves me an empty model

I am programming a Module for Contao in php.
I am using the function "Model::save()", which saves my data to the database.
But when I am trying to use the model after saving, it's just empty. I have no idea how this can happen.
The Code Snippet:
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
So in the var_dump before I save, everything is fine, but the second one doesn't show any data!
Does anybody got some ideas?
Edit2:
OK, here the complete code of the Module:
<?php
use Contao\Date;
use Contao\FilesModel;
use Contao\Input;
use Contao\Module;
use Contao\PageModel;
use Contao\RequestToken;
use Contao\Validator;
class ModuleReportData extends Module
{
protected $strTemplate = 'mod__reportdata';
public function generate()
{
if (TL_MODE == 'BE')
{
/** #var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ReportData ###';
$objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
return $objTemplate->parse();
}
return parent::generate();
}
public function compile()
{
$report_id = Input::get('r');
if($report_id){
$report = ReportModel::findByPk($report_id);
$project = ProjectModel::findBy('report_id', $report_id);
}else{
$report = new ReportModel();
$project = new ProjectModel();
}
$machine = new MachineModel();
$machines = [];
$next_step = false;
//get data for selectbox machines
$result = $this->Database->prepare("SELECT * FROM tl_sa_machines")->execute();
while($result->next())
{
$id = $result->id;
$machines[$id] = $result->type;
}
//Check if form was submitted
if(Input::post('submit_data')){
$report_data = Input::post('report_data');
$project_data = Input::post('project_data');
$machine_data = Input::post('machine_data');
$errors = [];
$next_step = true;
foreach($report_data as $key => $data)
{
if(empty($data)) continue;
switch ($key) {
case 'document_date':
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $data)) //###andere Formate hinzufügen
{
break;
}
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'customer':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'city':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'country':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'document_version':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'author':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'max_speed':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
}
}
$report->setRow($report_data);
foreach($project_data as $key => $data)
{
if(empty($data)) continue;
if(Validator::isAlphanumeric($data)) continue;
else {
$next_step = false;
$errors[$key] = "Error";
}
}
$project->setRow($project_data);
if($next_step)
{
$project->date_of_evaluation = strtotime($project->date_of_evaluation);
$report->document_date = strtotime($report->document_date);
//save and set report_data
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
$report = ReportModel::findByPK($report_id);
var_dump($report);
//save and set project_data
$project->report_id = $report->id;
$project->tstamp = time();
$project->save();
//session for transfering report_id to the next page
/* var_dump($report->id);
var_dump($report_id);
var_dump($project->report_id);
if($report_id) {
$_SESSION['report_id'] = $report_id;
}
else
{//var_dump($report_id);
//var_dump($report->id);
$report_id = $report->id;
$_SESSION['report_id'] = $report_id;
}
$jumpTo = PageModel::findByPk($this->jumpTo);
$url = $this->generateFrontendUrl($jumpTo->row());
$this->redirect($url);*/
}
}
$this->Template->report = $report;
$this->Template->project = $project;
$this->Template->machine = $machine;
$this->Template->machines = $machines;
$this->Template->errors = $errors;
$this->Template->request_token = RequestToken::get();
}
}
I have a form, to save new data, or to edit existing data. There are two different tables in the database I am trying to fill with data. FOr second one I need the new ID of the new row generated in this code. But it doesn't work because the model is empty after saving.
Edit3:
ProjectModel is just that simple:
use Contao\Model;
class ProjectModel extends Model{
protected static $strTable = "tl_sa_projects";
}
I just found out, it only happens when I use the save method on $report. It's working fine with $project!
Update:
It looks like I get an error when the refresh() method tries to select the new inserted databaserow with:
public function refresh()
{
$intPk = $this->{static::$strPk};
// Track primary key changes
if (isset($this->arrModified[static::$strPk]))
{
$intPk = $this->arrModified[static::$strPk];
}
// Reload the database record
$res = \Database::getInstance()->prepare("SELECT * FROM " . static::$strTable . " WHERE " . static::$strPk . "=?")
->execute($intPk);
var_dump($res);
$this->setRow($res->row());
}
Update 2:
Ok the problem is, that the "arrModified" contains an empty string as ID. Does anybody know where this array gets its elements?
Not the answer to your original question, but you should use
ProjectModel::findOneBy('report_id', $report_id);
instead of
ProjectModel::findBy('report_id', $report_id);
since you want to find only one specific project. findBy returns a Contao\Model\Collection (i.e. potentially multiple results) whereas findOneBy returns a Contao\Model.
Update:
Furthermore, your usage of setData and mergeRow is probably not intended this way. You should instead use
foreach ($project_data as $key => $val)
{
$project->$key = $val;
}
for instance.

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

"No data supplied for parameters in prepared statement" global insert function

I wrote an global function that getting array with keys and values, and inserting it to mysql db. something like this:
function insert_to_db($table, $data, $is_using_id) {
// I'm connecting to db before this code.
global $mysqli;
// .. Checking for errors ..
// .. if using id, remove the id from the values like this:
$columns = array_keys($data);
$values = array_values($data);
if ($is_using_id == true) {
unset($values[0]);
// Reorder the array after unset()
$values = array_merge($values);
}
// ..
// Generating text for use at the mysqli::prepare
$columns_text = "";
$i = 0;
while ($i < count($columns)) {
$column = $columns[$i];
if ($i == 0) {
$columns_text = $column;
} else {
$columns_text = $columns_text.", ".$column;
}
$i++;
}
unset($i);
unset($column);
$values_text = "";
// b_p_f is the $types string for mysqli-stmt::bind_param
$b_p_f = "";
// Generating text for use at the mysqli::prepare
$i = -1;
while ($i < count($values)) {
echo "\$i equals to {$i}<br>";
if ($is_using_id == true && $i == -1) {
// Null because id is calculated automatically by mysql
$values_text = "NULL";
} else if ($is_using_id == false && $i == 0) {
$value = $values[$i];
$values_text = "?";
if (is_numeric($value))
{
$b_p_f = 'i';
} else {
$b_p_f = 's';
}
} else {
$value = $values[$i];
$values_text = $values_text.", ?";
if (is_numeric($value))
{
echo "Value: {$value} Found as numberic<br>";
$b_p_f = $b_p_f.'i';
} else {
echo "Value: {$value} Found as non-numberic<br>";
$b_p_f = $b_p_f.'s';
}
}
$i++;
}
unset($i);
unset($value);
echo "b_p_f:";
var_dump($b_p_f);
echo " values:";
var_dump($values);
$stmt = $mysqli->prepare("INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
if (!$stmt) {
return array("error"=>"true", "error_mysqli"=>$mysqli->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
$stmt->bind_param($b_p_f, $values);
if ($stmt->execute()) {
return array("error"=>"false", "inserted_id"=>$mysqli->insert_id);
} else {
return array("error"=>"true", "error_stmt"=>$stmt->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
}
Then I am calling to the function:
function hash_password($password) {
$options = [ 'cost' => 12 ];
return password_hash($password, PASSWORD_BCRYPT,$options);
}
$data = array(
"ID" => NULL,
"first_name" => "Alexander",
"last_name" => "Margolis",
"email" => "shay24590#gmail.com",
"username" => "smartDonkey",
"password" => "Incorrect",
"birthday" => "12-12",
"date_added" => time(),
"total_points" => 0,
"cafe_added" => 0,
"review_placed"=> 0);
$data["password"] = hash_password($data["password"]);
var_dump ( insert_to_db("user", $data, true) );
And I see on the screen
array(3) {
["error"]=> string(4) "true"
["error_stmt"]=> string(53) "No data supplied for parameters in prepared statement" ["MORE"]=> string(178) "..."
}
Why am I getting this? What is the problem?
Also, If I pass the value instead of ? to the mysql::prepare, it works! So - it means that the problem is with mysqli stmt bind_param..
I know that this question similar to others, but I didn't found one that helps my problem. and sorry for my english and for the long function. thank you!
I've moved to PDO, and instead of calling $stmt->bind_param($b_p_f, $values); you can call $pdo_stmt->execute($values) where $values is an Array.

Categories