This question already has answers here:
PDO valid characters for placeholders
(2 answers)
Closed 2 years ago.
Hej.
I´m new to PHP but strugling to learn. i have found out that this is the way to handle database connection. Have debugged the code but have one stubborn thing left. Cant seem to wrap my brain around this errorcode. Any pointer in simple way so even i understand. ;-)
I am surfing this pages: https://www.php.net/manual/en/pdostatement.bindparam.php
Error-message:
Database connection establishedPDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\Test\dbtest.php:28 Stack trace: #0 C:\xampp\htdocs\Test\dbtest.php(28): PDOStatement->execute() #1 {main}
<?php
// Require needed classes
require_once('dbhandler.php');
// Create needed objects
$dbh = new DBHandler();
// Check if database connection established successfully
if ($dbh->getInstance() === null) {
die("No database connection");
}
//$datetime = date("Y-m-d H:i:s");
$epost = 'svante#telia.com';
$namn = 'Svante';
$användarnamn = 'Poffe';
$lösenord = '1596';
try {
$sql = "INSERT INTO users(epost, namn, användarnamn, lösenord) VALUES(:epost, :namn, :användarnamn, :lösenord)";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':epost', $epost, PDO::PARAM_STR);
$stmt->bindParam(':namn', $namn, PDO::PARAM_STR);
$stmt->bindParam(':användarnamn', $användarnamn, PDO::PARAM_STR);
$stmt->bindParam(':lösenord', $lösenord, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
echo $e;
}
?>
/Svante
It might be worth trying a simplified version that omits the special characters from the PHP variable and the assigned placeholders.
<?php
require_once('dbhandler.php');
$dbh = new DBHandler();
$e = 'svante#telia.com';
$n = 'Svante';
$a = 'Poffe';
$l = '1596';
$sql = "INSERT INTO users( `epost`, `namn`, `användarnamn`, `lösenord` ) VALUES( :e, :n, :a, :l )";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->bindParam(':e', $e, PDO::PARAM_STR);
$stmt->bindParam(':n', $n, PDO::PARAM_STR);
$stmt->bindParam(':a', $a, PDO::PARAM_STR);
$stmt->bindParam(':l', $l, PDO::PARAM_STR);
$stmt->execute();
Related
This question already has answers here:
PHP PDO - There is no active transaction
(2 answers)
Closed 2 years ago.
im trying to update 2 tables at once. from my research i have to use a transaction for this:
protected function myUpdateFunction(){
try{
$this->connect()->beginTransaction();
$itemID = filter_input(INPUT_POST, 'updateItemID');
$itemName = filter_input(INPUT_POST, 'updateItemName');
$itemDescription = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice = filter_input(INPUT_POST, 'updateItemPrice');
$itemStock = filter_input(INPUT_POST, 'updateItemStock');
$updateItemBtn = filter_input(INPUT_POST, 'updateItemBtn');
$sql = "UPDATE oopphp_items SET itemName = ?, itemDescription = ?, itemPrice = ?, itemStock = ? WHERE itemID = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice, PDO::PARAM_STR);
$stmt->bindParam(4, $itemStock, PDO::PARAM_INT);
$stmt->bindParam(5, $itemID, PDO::PARAM_INT);
$stmt->execute();
//wishlist
$itemID_fk = filter_input(INPUT_POST, 'updateItemID');
$itemName_fk = filter_input(INPUT_POST, 'updateItemName');
$itemDescription_fk = filter_input(INPUT_POST, 'updateItemDescription');
$itemPrice_fk = filter_input(INPUT_POST, 'updateItemPrice');
$sql = "UPDATE oopphp_wishlist SET itemName_fk = ?, itemDescription_fk = ?, itemPrice_fk = ? WHERE itemID_fk = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(1, $itemName_fk, PDO::PARAM_STR);
$stmt->bindParam(2, $itemDescription_fk, PDO::PARAM_STR);
$stmt->bindParam(3, $itemPrice_fk, PDO::PARAM_STR);
$stmt->bindParam(4, $itemID_fk, PDO::PARAM_INT);
$stmt->execute();
$this->connect()->commit();
}
catch(Exception $e){
echo $e->getMessage();
$this->connect()->rollBack();
}
}
i get the following error:
Fatal error: Uncaught PDOException: There is no active transaction
when i tried looking for answers they all said to put it inside a try-catch, which i already did. all examples i could find do it like this. as seen here: PHP PDO - There is no active transaction
i also found some people suggest adding these to the database file:
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
which also hasent done anything.
now if i just remove the code inside the catch() then the error goes away and i both my update queries work.
the only difference i could spot is that all examples dont have their database connection as a function.
so where i do:
$this->connect()->beginTransaction();
they do:
$pdo->beginTransaction();
and obviously same for commit() and rollBack(). though i cant imagine this being the problem. especially when it works perfectly if i remove the catch() content.
this is where i got the code from: https://thisinterestsme.com/php-pdo-transaction-example/
i seem to have the same code apart from the connect() vs $pdo.
my connect function:
protected function connect(){
try{
$dsn = 'mysql:host=' . $this->DB_HOST . ';dbname=' . $this->DB_NAME;
$pdo = new PDO($dsn, $this->DB_USER, $this->DB_PASS);
//setting default fetch mode
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//setting errors for exceptions for try/catch
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
return $pdo;
}
catch(PDOException $error){
echo 'Connection error: ' . $error->getMessage();
}
finally{
//$pdo = null;
}
}
i fixed it with the help of the comment, and a final note at the end if someone sees this later:
this line i mentioned: $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
made it so my CRUD didnt work anymore. the other 2 setAttribute() didnt cause errors with anything at this moment.
When you call connect(), you get a different PDO object each time. Thus,
$this->connect()->beginTransaction(); // pdo object 1
$this->connect()->commit(); // pdo object 4
PDO object 4 has no transaction in progress! the Exception is normal.
Quick fix :
in you try block
$pdo = $this->connect();
$pdo->beginTransaction();
.... // replace all $this->connect() by $pdo
$pdo->commit();
I use PHP PDO to update my data n database, but htis nt work coretly i still recive te same errror:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number.
how cna i fix this?
Hello I stil received this error but i can not find a mistake i made. when i throw away execute the code do not throw any error, but nothing change in my database.
I create code that should update a data in database i still receives this error:
I really want to now what make this error and hot to fixed i check with manual and everything look find, and i do not find any cntaradiction with my database in sql ask.
<?php
session_start();
include 'polaczenie_baz_danych.php';
$id_faktury = $_POST['id_faktury'];
$id_sprzedawcy = $_POST['id_sprzedawcy'];
$id_nabywcy = $_POST['id_nabywcy'];
if(isset($_POST['submit']))
{
$numer_faktury = $_POST['numer_faktury'];
$typ_faktury = $_POST['typ_faktury'];
$miejsce_wystawienia = $_POST['miejsce_wystawienia'];
$termin_wystawienia = $_POST['termin_wystawienia'];
$termin_sprzedazy= $_POST['termin_sprzedazy'];
$status_faktury = $_POST['status_faktury'];
$sposob_platnosci = $_POST['sposob_platnosci'];
$termin_platnosci = $_POST['termin_platnosci'];
$numer_konta = $_POST['numer_konta'];
$towar_usluga = $_POST['towar_usluga'];
$jm = $_POST['jm'];
$ilosc = $_POST['ilosc'];
$cena_netto = $_POST['cena_netto'];
$wartosc_netto = $_POST['wartosc_netto'];
$stawka_vat = $_POST['stawka_vat'];
$kwota_vat = $_POST['kwota_vat'];
$wartosc_brutto = $_POST['wartosc_brutto'];
$nazwa_nabywcy = $_POST['nazwa_nabywcy'];
$nip_nabywcy = $_POST['nip_nabywcy'];
$adres_nabywcy = $_POST['adres_nabywcy'];
$miasto_nabywcy = $_POST['miasto_nabywcy'];
$kod_pocztowy_nabywcy = $_POST['kod_pocztowy_nabywcy'];
$nazwa_sprzedawcy = $_POST['nazwa_sprzedawcy'];
$nip_sprzedawcy = $_POST['nip_sprzedawcy'];
$adres_sprzedawcy = $_POST['adres_sprzedawcy'];
$miasto_sprzedawcy = $_POST['miasto_sprzedawcy'];
$kod_pocztowy_sprzedawcy = $_POST['kod_pocztowy_sprzedawcy'];
$sql1 = ('UPDATE faktury SET
typ_faktury=:typ_faktury,
termin_wystawienia=:termin_wystawienia,
miejsce_wystawienia=:miejsce_wystawienia,
numer_faktury=:numer_faktury,
termin_sprzedazy=:termin_sprzedazy,
towar_usluga=:towar_usluga,
jm=:jm,
ilosc=:ilosc,
cena_netto=:cena_netto,
wartosc_netto=:wartosc_netto,
stawka_vat=:stawka_vat,
kwota_vat=:kwota_vat,
wartosc_brutto=:wartosc_brutto,
status_faktury=:status_faktury,
termin_platnosci=:termin_platnosci,
sposob_platnosci=:sposob_platnosci,
numer_konta=:numer_konta
WHERE id_faktury=:id_faktury');
$sql2 = ('UPDATE nabywcy SET nazwa_nabywcy=:nazwa_nabywcy,
nip_nabywcy=:nip_nabywcy,
adres_nabywcy=:adres_nabywcy,
miasto_nabywcy=:miasto_nabywcy,
kod_pocztowy_nabywcy=:kod_pocztowy_nabywcy
WHERE id_nabywcy=:id_nabywcy');
$sql3 =('UPDATE sprzedawcy SET nazwa_sprzedawcy=:nazwa_sprzedawcy, nip_sprzedawcy=:nip_sprzedawcy, adres_sprzedawcy=:adres_sprzedawcy, miasto_sprzedawcy=:miasto_sprzedawcy, kod_pocztowy_sprzedawcy=:kod_pocztowy_sprzedawcy
WHERE id_sprzedawcy=:id_sprzedawcy');
$performsql1 = $db->prepare($sql1);
$performsql1->bindValue(':typ_faktury',$typ_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_wystawienia',$termin_wystawienia, PDO::PARAM_STR);
$performsql1->bindValue(':miejsce_wystawienia',$miejsce_wystawienia, PDO::PARAM_STR);
$performsql1->bindValue(':numer_faktury',$numer_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_sprzedazy',$termin_sprzedazy, PDO::PARAM_STR);
$performsql1->bindValue(':towar_usluga', $towar_usluga, PDO::PARAM_STR);
$performsql1->bindValue(':jm',$jm, PDO::PARAM_STR);
$performsql1->bindValue(':ilosc',$ilosc, PDO::PARAM_INT);
$performsql1->bindValue(':cena_netto',$cena_netto, PDO::PARAM_STR);
$performsql1->bindValue(':wartosc_netto',($wartosc_netto), PDO::PARAM_STR);
$performsql1->bindValue(':stawka_vat',$stawka_vat, PDO::PARAM_STR);
$performsql1->bindValue(':kwota_vat',$kwota_vat, PDO::PARAM_STR);
$performsql1->bindValue(':wartosc_brutto',$wartosc_brutto, PDO::PARAM_STR);
$performsql1->bindValue(':sposob_platnosci',$sposob_platnosci, PDO::PARAM_STR);
$performsql1->bindValue(':status_faktury',$status_faktury, PDO::PARAM_STR);
$performsql1->bindValue(':termin_platnosci',$termin_platnosci, PDO::PARAM_STR);
$performsql1->bindValue(':numer_konta',$numer_konta, PDO::PARAM_STR);
$performsql1->bindValue(':id_faktury',$id_faktury, PDO::PARAM_INT);
$performsql1->execute();
unset($sql1);
$performsql2 = $db->prepare($sql2);
$performsql2->bindValue(':nazwa_nabywcy',$nazwa_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':nip_nabywcy',$nip_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':adres_nabywcy',$adres_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':miasto_nabywcy',$miasto_nabywcy, PDO::PARAM_STR);
$performsql2->bindValue(':kod_pocztowy_nabywcy', $kod_pocztowy_nabywcy, PDO::PARAM_STR);
$performsql1->bindValue(':id_nabywcy',$id_nabywcy, PDO::PARAM_INT);
$performsql2->execute();
unset($sql2);
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
$performsql3 = $db->prepare($sql3);
$performsql3->bindValue(':nazwa_sprzedawcy',$nazwa_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':nip_sprzedawcy',$nip_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':adres_sprzedawcy',$adres_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':miasto_sprzedawcy',$miasto_sprzedawcy, PDO::PARAM_STR);
$performsql3->bindValue(':kod_pocztowy_sprzedawcy', $kod_pocztowy_sprzedawcy, PDO::PARAM_STR);
$performsql1->bindValue(':id_sprzedawcy',$id_sprzedawcy, PDO::PARAM_NT);
$performsq3->execute();
unset($sql3);
}
?>
In $sql1 you have 18 parameters, but in $performsql1 you have only 17 bindings. You have lost 1 value to bind.
Upd.
You have WHERE id_faktury=:id_faktury' - it's 18th parameter. You have lost value ':id_faktury' to bind.
I am trying to write this basic function to get a value from a table.
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT :value AS value
FROM :from
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_STR);
$stmt->bindParam(':from', $from, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>
It gives this Fatal error:
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''project' WHERE id = '1'' at line 2' in /functions/getvalue.php:26 Stack trace: #0 /functions/getvalue.php(26): PDOStatement->execute() #1 /
test.php(24): getvalue('tarief', 'project', '1') #2 {main} thrown in /functions/getvalue.php on line 26
Although your idea of having such a function is excellent, the implementation is just terrible. Some essential drawbacks are:
you are connecting to database every time this function is called
this code is prone to SQL injection
yet it is awfully inflexible, letting you to run no query different from silly SELECT ... WHERE id. Eventually you will learn other queries and find this function unusable.
It should be a function that accepts an SQL query and array with parameters to bind:
<?php
//Returns the value of a query
function getvalue($sql, $params = array())
{
global $pdo;
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
}
require('includes/connect.php');
$name = getValue("SELECT name FROM users WHERE id =?",array($_GET['id']))
simple, robust and usable.
While connection string better to be moved into includes/connect.php
$dsn = "mysql:host=localhost;dbname=$database;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Try this (be sure $value and $from variables values are escaped):
<?php
function getvalue($value, $from, $id){
//Returns the value of a table
require('includes/connect.php');
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT " . $value . " AS value
FROM " . $from . "
WHERE id = :id
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
$return = $data['value'];
return $return;
}//function
?>
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 1 year ago.
First of all, this is my first meeting with MySQLi... I heard that MySQLi is better, but every time I wrote some code, I get
Fatal error: Call to a member function bind_param() on a non-object
My code is this:
<?php
/* Create a new mysqli object with database connection parameters */
$m = new mysqli('localhost', 'root', '', 'mysqlisample');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$ida=1;
$statement = $m->prepare("SELECT * FROM post WHERE `id` = ?");
$statement->bind_param("i",$ida);
$id = 0;
$post_title = '';
$post_content = '';
$statement->bind_result($id,$post_title,$post_content);
$statement->execute();
while ($statement->fetch()){
echo $id.' '.$post_title.' '.$post_content.'\n'; //These variables will get the values of the current row
}
?>
This is just one of many code sample that I read somewhere, but, none of them working.
What is the right way for executing MySQLi query and print the results?
i worked this out when going through the OReilly book, which was using the old mysql_stuff and none of the examples worked. obviously you'll need to modify it for your tables :) but it works for the tables i have. this will work for prepared statements:
<?php
//this file is just where my db info is, you can use the literal values
require 'login.php';
$db = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$stmt = $db->stmt_init();
$data = array("Emily Bronte", "Wuthering Heights", "Classic Fiction", "1847", "9780553212587");
if($stmt->prepare("INSERT INTO classics(author, title, category, year, isbn) VALUES(?,?,?,?,?)"))
{
$stmt->bind_param('sssss', $data[0], $data[1], $data[2], $data[3], $data[4]);
$stmt->execute();
$stmt->close();
}
?>
this will work for queries:
<?php
require_once 'login.php';
$dbt = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($dbt->connect_errno)
die("Unable to connect to MySQL: " . $dbt->connect_errno);
$results = $dbt->query("SELECT * FROM cats");
if (!$results)
die ("Database access failed: " . $db->error);
$dbt->close();
echo "<table><tr> <th>Id</th> <th>Family</th>
<th>Name</th><th>Age</th></tr>";
for ($j = 0 ; $j < $results->num_rows ; ++$j)
{
$row = $results->fetch_row();
echo "<tr>";
for ($k = 0 ; $k < sizeof($row) ; ++$k)
echo "<td>$row[$k]</td>";
echo "</tr>";
}
echo "</table>";
?>
The problem is that $statement->bind_param("i",$ida); returns false, so you can't call the method bind_param on false
See: http://php.net/manual/de/mysqli.prepare.php
Try:
mysqli_stmt_bind_param($statement, "i", $ida);
instead of:
$statement->bind_param("i",$ida);
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks