phpSlim post function inserting null data - php

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);

Related

PDO INSERT not working but no errors

I made this script to generate a string and insert it into a database,
but it doesn't insert into the database even though i get no errors what so ever.
$pare = $id;
$time_stamp = date('H:m');
$token = 'token'. md5($pare . $time_stamp);
echo " Token: -" . $token;
try {
$database = $this->server->connect_to_database('3250900');
$sql_query_string = "INSERT INTO `authentication_tokens` (`id`, `user_id`, `token`, `timestamp`) VALUES (:n, :user_id, :token, :time_stamp)";
$statement = $database->prepare($sql_query_string); //Prepare the sql statement
$statement->execute([ ':n' => NULL,
':user_id' => $pare,
':token' => $token,
':time_stamp' => $time_stamp]); //execute query
} catch (Exception $e) {
echo $e;
}
print_r($statement);
Try this code:
$pare = $id;
$time_stamp = date('H:m');
$token = 'token'. md5($pare . $time_stamp);
echo " Token: -" . $token;
try {
$database = $this->server->connect_to_database('3250900');
$stmt = $database ->prepare ("INSERT INTO `authentication_tokens` (`id`, `user_id`, `token`, `timestamp`) VALUES (:n, :user_id, :token, :time_stamp)");
$stmt -> bindParam(':n', NULL);
$stmt -> bindParam(':user_id', $pare);
$stmt -> bindParam(':token', $token);
$stmt -> bindParam(':timestamp', $time_stamp);
$result = $stmt -> execute();
}
catch (PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
if ($result) {
return $stmt->rowCount();
}

PHP Post-Method prepare() returns False

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.

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.

PHP & PDO PHP Notice: Undefined property: Database::$photo?

Okay so here is the code that I am using
function AddProducts($aTitle, $aDescription, $aPrice, $aQty, $aPhoto)
{
try {
$stmt = $this->pdo->prepare("INSERT INTO products(title, price, description, qty, photo) VALUES(:title, :price, :description, :qty, :photo)");
if(!$stmt){
$err = $this->pdo->errorInfo();
throw new RuntimeException('PRODUCT INSERT FAILED: '.$err[2]);
}
$stmt->bindValue(':title', $this->title, PDO::PARAM_STR);
$stmt->bindValue(':description', $this->description, PDO::PARAM_STR);
$stmt->bindValue(':price', $this->price, PDO::PARAM_INT);
$stmt->bindValue(':qty', $this->qty, PDO::PARAM_INT);
$stmt->bindValue(':photo', $this->photo, PDO::PARAM_STR);
$stmt->execute();
}catch (PDOException $e) {
echo $e->getMessage();
}
}
$addProducts = $database->AddProducts('Ford Mustang', 'This is a Descriptiom', 299.99, 1, 'images/includes/5.jpg');
The database class and database call function work. Also if you spot anything that could be improved, please point it out as I am trying to learn.
Why $this->photo? Do you really have this property in your class? Or maybe you need something like this?
function AddProducts($aTitle, $aDescription, $aPrice, $aQty, $aPhoto)
{
try {
$stmt = $this->pdo->prepare("INSERT INTO products(title, price, description, qty, photo) VALUES(:title, :price, :description, :qty, :photo)");
if(!$stmt){
$err = $this->pdo->errorInfo();
throw new RuntimeException('PRODUCT INSERT FAILED: '.$err[2]);
}
$stmt->bindValue(':title', $aTitle, PDO::PARAM_STR);
$stmt->bindValue(':description', $aDescription, PDO::PARAM_STR);
$stmt->bindValue(':price', $aPrice, PDO::PARAM_INT);
$stmt->bindValue(':qty', $aQty, PDO::PARAM_INT);
$stmt->bindValue(':photo', $aPhoto, PDO::PARAM_STR);
$stmt->execute();
}catch (PDOException $e) {
echo $e->getMessage();
}
}
$addProducts = $database->AddProducts('Ford Mustang', 'This is a Descriptiom', 299.99, 1, 'images/includes/5.jpg');

Categories