This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed last month.
I'm trying to come up with a way to control what happends if some UPDATE/INSERTS into a BD fail.
private $db;
public function __construct() {
$dsn = 'mysql:dbname=BDNAME;host=localhost';
$this->db = new PDO($dsn, 'USEER', 'PASSWORD', array('charset' => 'utf8'));
}
public function createnewthingtodo($what,$where,$when,$how,$done){
$sql= "INSERT INTO TODOLIST (what,where,when,how,done) VALUES (:what, :where, :when, :how, :done)";
$st = $this->db->prepare ($sql);
$st->bindValue(':what',$what);
$st->bindValue(':where',$where);
$st->bindValue(':when',$when);
$st->bindValue(':how',$how);
$st->bindValue(':done',$done);
if($st->execute()){
return true;
}else{
return false;
}
}
This example is returning always false, if i delete the last "if" and put the execution part just below the last binvalue, it works just fine, but then i end up with no error handling, any ideas on how can i achieve this? Thanks for your time.
Related
This question already has answers here:
delete using where and or
(4 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I'm coding a blog to get experience with php.
I want the admin to be able to delete a post, but when I click the delete-button which should actually bring me to a function that deletes the post I get the error Call to a member function execute() on boolean.
Here is the code of the postsRepository.php which interacts with the database and the function in the postsAdminController.php:
public function deletePost($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");
$stmt->execute([
'id' => $id
]);
}
public function deletePost()
{
$id = $_GET['id'];
if ($this->postsRepository->deletePost($id)) {
header("Location: posts-admin");
return;
} else {
}
}
I've var_dumped the $id right before the $stmt, it's correct and the shown error says the it is because of $stmt->execute([.
The $stmt is stated as false when I var_dumped it, but why?
The correct syntax for DELETE is
DELETE FROM tableName WHERE ...
Remove the * in your query.
$stmt is false because "If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling)."
For more informations, check the documentation
This question already has answers here:
What is the difference between bindParam and bindValue?
(7 answers)
Closed 7 years ago.
This is my php code:
public function update($table,$fields_and_values,$condition_field,$condition_field_value)
{
$query="UPDATE $table SET ";
foreach($fields_and_values as $field=>$value) $query.=($field."=:".$field." ,");
$query.=" ";
$query=str_replace(", "," WHERE ",$query);
$query.=($condition_field."='".$condition_field_value."'");
echo $query;
$stmt=$this->conn->prepare($query);
foreach($fields_and_values as $field=>$value) $stmt->bindParam(":".$field,$value);
$stmt->execute();
}
and this is how i call the function in my class:
$db=new db_connection('localhost','root','','maps');
$db->connect();
$arr=array('username'=>'testfromnewclass3','password'=>'123456');
$db->update('users',$arr,'username','term');
$db->disconnect();
It doesn't matter what the other functions like disconnect do! They work correctly.
My problem is that when this command executes, both username and password become 123456 !
And this is what i get from that echo $query:
UPDATE users SET username=:username ,password=:password WHERE username='term'
Is something wrong with my function? and if so how can i fix it?
Use $stmt->bindValue($field, $value);
instead of $stmt->bindParam(":".$field,$value);
Check this to understand difference between PDOStatement::bindParam() and PDOStatement::bindValue()
This question already has answers here:
Creating default object from empty value in PHP?
(18 answers)
Closed 8 years ago.
I am stuck. I have spent two days looking thru all the references I can find and I can’t figure out why this will not work! I get the error: "Creating default object from empty value." Bellow is my SQL statement and my parameters array.
$sql_insert = "
INSERT INTO vrm_vrd_submission_tbl (vrm_vrd_nmbr_id, vrm_vrd_sub_type_id, vrm_vrd_sub_date, vrm_vrd_min_form_date, vrm_vrd_sub_quantity, county_id, pers_emp_pre_id, election_general_info_id ,vrm_vrd_sub_submitter_name, vrm_vrd_compliance_rules_id)
VALUES(:vrm_vrd_nmbr_id,
:vrm_vrd_sub_type_id,
:vrm_vrd_sub_date,
:vrm_vrd_min_form_date,
:vrm_vrd_sub_quantity,
:county_id,
:pers_emp_pre_id,
:election_general_info_id,
:vrm_vrd_sub_submitter_name,
:vrm_vrd_compliance_rules_id)
";
$sql_parms=array(":vrm_vrd_nmbr_id"=>$vrm_vrd_nmbr_id, ":vrm_vrd_sub_type_id
"=>$data['vrm_vrd_sub_type_id'],
":vrm_vrd_sub_date"=>trim($data['vrm_vrd_sub_date']),
":vrm_vrd_min_form_date"=>trim($data['vrm_vrd_min_form_date']),
":vrm_vrd_sub_quantity"=>trim($data['vrm_vrd_sub_quantity']), ":county_id
"=>$data['county_id'],":pers_emp_pre_id "=>$data['pers_emp_pre_id'],
":election_general_info_id"=>$election_general_info_id,
":vrm_vrd_sub_submitter_name"=>$vrm_vrd_sub_submitter_name,
":vrm_vrd_compliance_rules_id"=> $vrm_vrd_compliance_rules_id);
$ret_val=$db->db_bound_query($sql_insert, $sql_parms);
Method being called in my database class:
public function db_bound_query($qry_str, $parms_array){
$log = new error_log_class;
$db_conn = self::_connect();
if(!$exec_str= $db_conn->prepare($qry_str)){
$log->save_to_log($qry_str,__LINE__,__FILE__,"Failed to perpare.");
}
$val="";
foreach($parms_array as $parm ->$val){
$exec_str->bindParam($parm,$val);
}
$res=$exec_str->execute();
$results= $exec_str->fetchAll(PDO::FETCH_ASSOC);
}
EDIT:
I changed this method to the following as suggensted by #iamsleepy and #MrCode. But I am getting the error I was originally chasing which is "Invalid Parameter number".
public function db_bound_query($qry_str, $parms_array){
$log = new error_log_class;
$db_conn = self::_connect();
if(!$exec_str= $db_conn->prepare($qry_str)){
$log->save_to_log($qry_str,__LINE__,__FILE__,"Failed to perpare.");
}
$res=$exec_str->execute($parms_array );
$results= $exec_str->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
You have a space at the end of this parameter name:
":pers_emp_pre_id "=>$data['pers_emp_pre_id']
^ here
Should be:
":pers_emp_pre_id"=>$data['pers_emp_pre_id']
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 9 years ago.
The following function is not working and i cannot see why.
function nuevoContacto($_POST) {
try {
include('func/usarBases.php');
$mensaje="INSERT INTO `t_contactos`(`id_c`, `nombre`, `telefono`, `telefono2`, `corto`, `celular1`, `celular2`, `email`, `puesto`, `id_a`) VALUES (NULL,'$_POST[nombre]','$_POST[tel1]','$_POST[tel2]','$_POST[corto]','$_POST[cel1]','$_POST[cel2]','$_POST[email]','$_POST[puesto]','$_POST[id_a]')";
$hacerConsulta = $base->prepare($mensaje);
$hacerConsulta->execute();
}
catch( PDOException $e) {
echo "<p>Error Connection: " .$e->getMessage()."</p>";
}
$hacerConsulta=null;
}
Once it is called the code breaks and nothing further is executed.
but when you use it inside the main code it works
Sorry i reedited the source and then is still not working, in the include usarBases.php is the conector pdo called $base
What it have to be
function nuevoContacto($base)
{
$sql = "INSERT INTO t_contactos VALUES (NULL,?,?,?,?,?,?,?,?,?)";
$data = array(
$_POST['nombre'],
$_POST['tel1'],
$_POST['tel2'],
$_POST['corto'],
$_POST['cel1'],
$_POST['cel2'],
$_POST['email'],
$_POST['puesto'],
$_POST['id_a']
);
$stmt = $base->prepare($sql);
$stmt->execute($data);
}
have to be called with $base as a parameter instead of $_POST
You're lacking a database connection in your function. Add the following to the very beginning of your function:
global $base;
When you add global $base to your function you'll be able to use it within your function without having to re-write the whole thing.
Unrelated note, but worth mentioning.
You are open to SQL injections and you're not using prepared statements as you should. You should be using placeholders and binding them later instead of passing they directly into your query.
And a tip for next time:
State in your question what isn't working. What your expectation is and what actually happens.
This question already has answers here:
checking if SQL query was excuted in PDO [duplicate]
(2 answers)
Closed 9 years ago.
I would like to know how to check if the insert statement is executed or not.
my current code of checking it is this:
$query = $conn->prepare("INSERT INTO editlog VALUES('',:whoadd,:doing,NOW())");
$query-> execute(array(':whoadd' => $whoadd,':doing' => $doing));
if ($query->rowCount() > 0) {
// insert statement have been executed
}
else
{
// something went wrong
}
is there a better way than using $query->rowCount() > 0 ? I have heard that rowCount() itself runs a query to mysql database..so, what is a good alternative?
As Mark Parnell suggested, wrapping the execute call in an if statement does the trick. It might prove useful later on to set some attributes of your database object, too:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Causing PDO to throw exceptions (PDOException) in case a query fails. You can set these attributes by passing an array as fourth parameter to the constructor:
$pdo = new PDO('mysql:dbname=foobar;host=127.0.0.1','your','pass',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ'));
For example, here's a full list of all attributes that can be specified.
Check the return value of the execute call:
if ($query->execute(array(':whoadd' => $whoadd,':doing' => $doing))) {
// insert statment have been excuted
}
else
{
// something went wrong
}
PDOStatement::execute() itself will return true on success or false on failure.