PHP Post-Method prepare() returns False - php

Here is the Problem, I want to create a Post-Method for my Webservice. I'm uing the Slim Framework with PHP7 and an SQLite3 Database. I have the following code implemented:
$app->post('/api/generalinformation', function ($request) {
try {
$db = new PDO("sqlite:D:/Schule/notfunk_app/IPNF.db") or die("Cannot open Database");
$query = "insert into nlv_GeneralInformation (SystemID, InformationID, Title, Description, Importance) values (:SystemID, :InformationID, :Title, :Description, :Importance);";
$stmt = $db->prepare($query);
if($stmt === false){
die("prepare() failed");
}
$SystemID = $request->getparsedBody()["SystemID"];
$InformationID = $request->getparsedBody()["InformationID"];
$Title = $request->getparsedBody()["Title"];
$Description = $request->getparsedBody()["Description"];
$Importance = $request->getparsedBody()["Importance"];
$stmt->bindParam(":SystemID", $SystemID, PDO::PARAM_INT);
$stmt->bindParam(":InformationID", $InformationID, PDO::PARAM_INT);
$stmt->bindParam(":Title", $Title, PDO::PARAM_STR);
$stmt->bindParam(":Description", $Description, PDO::PARAM_STR);
$stmt->bindParam(":Importance", $Importance, PDO::PARAM_INT);
$stmt->execute();
$db = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
});
But the prepare() funktion always returns me false. I've testet the query and it works.

Related

phpSlim post function inserting null data

i am using php slim framework 3
my function is inserting null instead of data
function addstud(Request $request, Response $response)
{
$stud = $request->getParsedBody();
$sql = "INSERT INTO students (`name`, `username`, `password`) VALUES (':name', ':username', ':password')";
try {
$db = GetDatabase();
$stmt = $db->prepare($sql);
$stmt->bindParam("name", $stud->name);
$stmt->bindParam("username", $stud->username);
$stmt->bindParam("password", $stud->password);
$stmt->execute();
$stud->id = $db->lastInsertId();
$db = null;
echo json_encode($stud);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
can any one help me out ?
You're binding parameters incorrectly: you forgot colon. So, instead of
$stmt->bindParam("name", $stud->name);
$stmt->bindParam("username", $stud->username);
$stmt->bindParam("password", $stud->password);
You should do
$stmt->bindParam(":name", $stud->name);
$stmt->bindParam(":username", $stud->username);
$stmt->bindParam(":password", $stud->password);

Table value are not changing

There is my code of EDIT.php DB_Functions,and g.php..I'm not geting where is the fault is anyone here who can help me to find out mistake on my code
Every things happen as easy but change in table is not reflecting..my SQL query is working properly on XAMP server..
It may be silly mistake but not able to find it..
edit.php
<?php
//error_reporting(0);
include("class_db.php");
include_once('DB_Functions.php');
if (isset ($_GET['edit_id']))
{
$id=$_GET['edit_id'];
{
if(isset($_POST['nam']))
{
$id =($_POST['edit_id']);
$name=($_POST['name']);
$lastname=($_POST['lastname']);
$email=($_POST['email']);
$duser=($_POST['duser']);
$pass=($_POST['pass']);
$mob=($_POST['mob']);
$website=($_POST['website']);
$result = file_get_contents('http://localhost/rajju/demo/webservises/webservises/webservices/g.php?action=update_details&id='.$id.'&name='.$name.'&lastname='.$lastname.'&email='.$email.'&duser='.$duser.'&pass='.$pass.'&mob='.$mob.'&website='.$website);
$result = json_decode($result, true);
if($result == 'success'){
header("location:http://localhost/rajju/demo/webservises/webservises/webservices/list.php");
}
else{
print_r($result);
}
}
}
}
$select =mysql_query("select * from users where id=$id");
$var = mysql_fetch_object($select);
?>
DB_Functions.php
public function updateUser($id,$name,$lastname,$email,$duser,$pass,$mob,$website)
{
$app_list =mysql_query("UPDATE users SET name='".$name."',lastname='".$lastname."',email='".$email."',duser='".$duser."',pass='".$pass."',mob='".$mob."',website='".$website."' WHERE id='".$id."'");
if ($app_list) {
return true;
} else {
return false;
}
}
g.php
else if($tag == 'update_details')
{
$db = new DB_Functions();
//$id = ($_GET['id']);
$name=($_GET['name']);
$lastname=($_GET['lastname']);
$email=($_GET['email']);
$duser=($_GET['duser']);
$pass=($_GET['pass']);
$mob=($_GET['mob']);
$website=($_GET['website']);
//exit (json_encode($name));
if ($db ->updateUser($name,$lastname,$email,$duser,$pass,$mob,$website))
{
exit (json_encode('success'));
}else
{
exit (json_encode('errorzz'));
}
}
The following should work. Note this still wont totally protect you against xss and other attacks. However its a lot better than using mysql_query!! Additionally, you should sanatise and check your incoming $_GET params and Salt+Hash your passwords.
<?php
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE users SET name=:name, lastname=:lastname, email=:email, duser=:duser, pass=:pass, mob=:mob, website=:website, WHERE id=:id";;
$st = $conn->prepare( $sql );
$st->bindValue(":name", $name, PDO::PARAM_STR);
$st->bindValue(":lastname", $lastname, PDO::PARAM_STR);
$st->bindValue(":email", $email, PDO::PARAM_STR);
$st->bindValue(":duser", $duser, PDO::PARAM_STR);
$st->bindValue(":pass", $pass, PDO::PARAM_STR);
$st->bindValue(":mob", $mob, PDO::PARAM_STR);
$st->bindValue(":website", $website, PDO::PARAM_STR);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->execute();
?>

PHP PDO insert operation failing

I am new to PDO and I am having a problem with the following insert operation. It ends up always in the else case (returning 0).
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass");
try {
$stmte = $pdoConnection->prepare("INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES (?, ?, ?, NOW(), ?, ?)");
$stmte->bindParam(1, $usuarioId , PDO::PARAM_INT);
$stmte->bindParam(2, $tipoFaturaId , PDO::PARAM_INT);
$stmte->bindParam(3, $parametrosValidadores , PDO::PARAM_STR);
$stmte->bindParam(4, $identificadorExtra , PDO::PARAM_STR);
$stmte->bindParam(5, $optin , PDO::PARAM_INT);
$executarInclusao = $stmte->execute();
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
} catch (PDOException $e) {
return -1;
}
}
It used to work when I was using mysql_query like this:
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$db_connection = mysql_connect( "host", "user", "pass" ) or die( mysql_error() );
mysql_select_db( "database" ) or die( mysql_error() );
$insert_query = "INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES ('".$usuarioId."', '".$tipoFaturaId."', '".$parametrosValidadores."', NOW(), '".$identificadorExtra."', '".$optin."');";
$query_return = mysql_query($insert_query);
$new_id = mysql_insert_id();
if($query_return) {
return $new_id; // OK
}
else {
return 0;
}
}
Right now I am failing to see what could be wrong. Any suggestions?
You need to set this
$pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
You will now get the error because you have set the PDO error mode to exception.
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass");
$pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$stmte = $pdoConnection->prepare("INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES (?, ?, ?, NOW(), ?, ?)");
$stmte->bindParam(1, $usuarioId , PDO::PARAM_INT);
$stmte->bindParam(2, $tipoFaturaId , PDO::PARAM_INT);
$stmte->bindParam(3, $parametrosValidadores , PDO::PARAM_STR);
$stmte->bindParam(4, $identificadorExtra , PDO::PARAM_STR);
$stmte->bindParam(5, $optin , PDO::PARAM_INT);
$executarInclusao = $stmte->execute();
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
Use this
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
and then you can change this:
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
for this:
return $pdoConnection->lastInsertId();
Because if something go wrong with query, $stmte->execute() throw PDOException

PDO unable to insert datas into database

I'm newbie with pdo. Here i'm trying to insert the datas into database using this below coding. But, i cannot able to insert the datas into database. I'm getting this following error
Fatal error: Call to a member function prepare() on a non-object
I searched on SO and internet about this error. Some people says add global $conn; at the top of your code. I added these code but i'm getting same error. Anyone tell me what should i do if i want to clear this error?
Config.php
<?php
$user = "root";
$password = "password";
try
{
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
'DATABASE CONNECTION ERROR' .$e->getMessage();
}
?>
**Database.php**
<?php
session_start();
include('config.php');
if(isset($_POST['submit_val']))
{
$cmeal = $_POST['meal'];
try
{
$stmt = $conn->prepare("INSERT INTO ebmealplans ( MealPlanName, CreatedOn ) VALUES ( :cmeal, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':cmeal', $cmeal, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
$croom = $_POST['room'];
$ref_key = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebroomtypes ( RoomTypeName, CreatedOn ) VALUES ( :croom, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':croom', $croom, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
<*************** UPDATED CODES ***************>
$creference = $_POST['reference'];
$crefdate = $_POST['refdate'];
$ccin = $_POST['cin'];
$cout = $_POST['out'];
$cgname = $_POST['gname'];
$ctotaladults = $_POST['totaladults'];
$cchildrens = $_POST['childrens'];
$cinfants = $_POST['infants'];
$cgphone = $_POST['gphone'];
$cgemail = $_POST['gemail'];
$cgfax = $_POST['gfax'];
$cgaddress1 = $_POST['gaddress1'];
$cgaddress2 = $_POST['gaddress2'];
$cregion = $_POST['region'];
$ccity = $_POST['city'];
$cstate = $_POST['city_state'];
$ccountry = $_POST['country'];
$ccurrency = $_POST['currency'];
$ccurrencyto = $_POST['tocurrency'];
$camount = $_POST['camount'];
$ccurrencyvalue = $_POST['currencyvalue'];
$voucher_fk = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchers ( VoucherReference, BookingDate, CheckIndate, CheckOutDate, MealPlanID_Fk, RoomTypeID_Fk, GuestName, TotalAdults, Childrens, Infants, GuestPhone, GuestEmail, GuestFax, GuestAddressLine1, GuestAddressLine2, GuestRegion, GuestCity, GuestState, GuestCountry, GuestCurrency, GuestCurrencyTo, CurrencyAmount, GuestCurrencyValue, VoucherCreatedOn ) VALUES ( :reference, :refdate, :ccin, :cout, :r_key, :r_key, :gname, :totaladults, :childrens, :infants, :gphone, :gemail, :gfax, :gaddress1, :gaddress2, :gregion, :city, :state, :country, :currency, :currencyto, :amount, :currencyvalue, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':reference', $creference, PDO::PARAM_STR);
$stmt->bindParam(':refdate', $crefdate, PDO::PARAM_STR);
$stmt->bindParam(':ccin', $ccin, PDO::PARAM_STR);
$stmt->bindParam(':cout', $cout, PDO::PARAM_STR);
$stmt->bindParam(':r_key', $ref_key, PDO::PARAM_STR);
$stmt->bindParam(':r_key', $ref_key, PDO::PARAM_STR);
$stmt->bindParam(':gname', $cgname, PDO::PARAM_STR);
$stmt->bindParam(':totaladults', $ctotaladults, PDO::PARAM_STR);
$stmt->bindParam(':childrens', $cchildrens, PDO::PARAM_STR);
$stmt->bindParam(':infants', $cinfants, PDO::PARAM_STR);
$stmt->bindParam(':gphone', $cgphone, PDO::PARAM_STR);
$stmt->bindParam(':gemail', $cgemail, PDO::PARAM_STR);
$stmt->bindParam(':gfax', $cgfax, PDO::PARAM_STR);
$stmt->bindParam(':gaddress1', $cgaddress1, PDO::PARAM_STR);
$stmt->bindParam(':gaddress2', $cgaddress2, PDO::PARAM_STR);
$stmt->bindParam(':gregion', $cregion, PDO::PARAM_STR);
$stmt->bindParam(':city', $ccity, PDO::PARAM_STR);
$stmt->bindParam(':state', $cstate, PDO::PARAM_STR);
$stmt->bindParam(':country', $ccountry, PDO::PARAM_STR);
$stmt->bindParam(':currency', $ccurrency, PDO::PARAM_STR);
$stmt->bindParam(':currencyto', $ccurrencyto, PDO::PARAM_STR);
$stmt->bindParam(':amount', $camount, PDO::PARAM_STR);
$stmt->bindParam(':currencyvalue', $ccurrencyvalue, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
<*************** UPDATED CODES ***************>
foreach ( $_POST['slno'] as $key=>$slno )
{
$date = $_POST['date'][$key];
$particulars = $_POST['particulars'][$key];
$noofnights = $_POST['noofnights'][$key];
$rate = $_POST['rate'][$key];
$price = $_POST['price'][$key];
$tax = $_POST['tax'][$key];
$nettotal = $_POST['nettotal'];
$totalamount = $_POST['totalamount'];
$finaltotal = $_POST['finaltotal'];
$c_date = $date;
$c_slno = $slno;
$c_particulars = $particulars;
$c_noofnights = $noofnights;
$c_rate = $rate;
$c_price = $price;
$c_tax = $tax;
$c_nettotal = $nettotal;
$c_totalamount = $totalamount;
$c_finaltotal = $finaltotal;
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchertariffs ( TariffSlNo, TariffDate, TariffParticulars, NoOfNights, TariffRate, TariffPrice, TariffTax, TariffNetTotal, TariffAddTotal, TariffFinalTotal, VoucherID_Fk, CreatedOn ) VALUES ( :c_slno, :c_date, :c_particulars, :c_noofnights, :c_rate, :c_price, :c_tax, :c_nettotal, :c_totalamount, :c_finaltotal, :voucher_fk, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':c_slno', $c_slno, PDO::PARAM_STR);
$stmt->bindParam(':c_date', $c_date, PDO::PARAM_STR);
$stmt->bindParam(':c_particulars', $c_particulars, PDO::PARAM_STR);
$stmt->bindParam(':c_noofnights', $c_noofnights, PDO::PARAM_STR);
$stmt->bindParam(':c_rate', $c_rate, PDO::PARAM_STR);
$stmt->bindParam(':c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam(':c_tax', $c_tax, PDO::PARAM_STR);
$stmt->bindParam(':c_nettotal', $c_nettotal, PDO::PARAM_STR);
$stmt->bindParam(':c_totalamount', $c_totalamount, PDO::PARAM_STR);
$stmt->bindParam(':c_finaltotal', $c_finaltotal, PDO::PARAM_STR);
$stmt->bindParam(':voucher_fk', $voucher_fk, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
$conn = null;
}
}
?>
You did not print your exception. If you have any exception you will not get it. and i think problem in your $conn= null;
$conn = null; this line makes your connection object invalid and after executing this line you have invalid pdo object.for this you have got this error in loop. it should execute all other query before this line is executed. just remove this line. and print your exception message like this:
Try this:
<?php
session_start();
include('config.php');
if(isset($_POST['submit_val']))
{
$cmeal = $_POST['meal'];
try
{
$stmt = $conn->prepare("INSERT INTO ebmealplans ( MealPlanName, CreatedOn ) VALUES ( :cmeal, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':cmeal', $cmeal, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die('Query failed to insert into database ' .$e->getMessage());
}
$croom = $_POST['room'];
$ref_key = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebroomtypes ( RoomTypeName, CreatedOn ) VALUES ( :croom, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':croom', $croom, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die( 'Query failed to insert into database ' .$e->getMessage());
}
foreach ( $_POST['slno'] as $key=>$slno )
{
$date = $_POST['date'][$key];
$particulars = $_POST['particulars'][$key];
$noofnights = $_POST['noofnights'][$key];
$rate = $_POST['rate'][$key];
$price = $_POST['price'][$key];
$tax = $_POST['tax'][$key];
$nettotal = $_POST['nettotal'];
$totalamount = $_POST['totalamount'];
$finaltotal = $_POST['finaltotal'];
$c_date = $date;
$c_slno = $slno;
$c_particulars = $particulars;
$c_noofnights = $noofnights;
$c_rate = $rate;
$c_price = $price;
$c_tax = $tax;
$c_nettotal = $nettotal;
$c_totalamount = $totalamount;
$c_finaltotal = $finaltotal;
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchertariffs ( TariffSlNo, TariffDate, TariffParticulars, NoOfNights, TariffRate, TariffPrice, TariffTax, TariffNetTotal, TariffAddTotal, TariffFinalTotal, VoucherID_Fk, CreatedOn ) VALUES ( :c_slno, :c_date, :c_particulars, :c_noofnights, :c_rate, :c_price, :c_tax, :c_nettotal, :c_totalamount, :c_finaltotal, :voucher_fk, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':c_slno', $c_slno, PDO::PARAM_STR);
$stmt->bindParam(':c_date', $c_date, PDO::PARAM_STR);
$stmt->bindParam(':c_particulars', $c_particulars, PDO::PARAM_STR);
$stmt->bindParam(':c_noofnights', $c_noofnights, PDO::PARAM_STR);
$stmt->bindParam(':c_rate', $c_rate, PDO::PARAM_STR);
$stmt->bindParam(':c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam(':c_tax', $c_tax, PDO::PARAM_STR);
$stmt->bindParam(':c_nettotal', $c_nettotal, PDO::PARAM_STR);
$stmt->bindParam(':c_totalamount', $c_totalamount, PDO::PARAM_STR);
$stmt->bindParam(':c_finaltotal', $c_finaltotal, PDO::PARAM_STR);
$stmt->bindParam(':voucher_fk', $voucher_fk, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die('Query failed to insert into database ' .$e->getMessage());
}
//$conn = null;
}
}
?>

how to return a value from a method inside another method php

i got two methods.one method is to insert data and the other one is to get the id of the inserted data. i tried several test but it doesn't give any return value.is it possible to pass a return value from another method?
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
//$log = $this->getSessionID($email);
return $this->getSessionID($email);
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
public function getSessionID($email) {
try {
//global $bcrypt;
$query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");
$query->bindValue(1, $email);
$query->execute();
$data1 = $query->fetch();
$id = $data1['id'];
//echo $id;
return $id;
} catch(PDOException $e) {
die($e->getMessage());
}
}
and the returning page is here:
if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
session_regenerate_id(true);
$_SESSION['id'] = $data;
//print_r($_SESSION);
header('location: registry.php');
exit();
}
Use the lastInsertID() method on your query object rather than a second query
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
$insertId = $query->lastInsertId(); // <!-- Use this instead of a second query
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
Its also important to note that you are not inserting the 'email address' into your database, so there is no way for the query to find it by that field if you were to use another SELECT statement. You might want to complete your INSERT statement.

Categories