PDO INSERT not working but no errors - php

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

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

Notice: Array to string conversion Error: Array

This one has had me stumped for a while I cannot see why I am getting this error. This is my code
<?php
include('include/auth.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(isset($_POST['submit']))
{
$serverName = "localhost";
$connectionInfo = array( "Database"=>"db", "UID"=>"sa", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$pathfinderid = $_POST['pathfinderid'];
$locationid = $_POST['locationid'];
$status = $_POST['status'];
$statusnote = $_POST['statusnote'];
$user = $_SESSION['SESS_USER'];
$date = new DateTime();
$ims = 'New Device Added';
if(empty($pathfinderid) || empty($locationid) || empty($status) || empty($statusnote)) {
echo "<div id='source'><p style='color:red;'>Please complete all fields</p></div>";
}
else
{
//SQL to check if pathdnder exsists
$stmt = sqlsrv_query( $conn, "SELECT * FROM devices WHERE pathfinderid='$pathfinderid'");
//If statement to check rows
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true) {
echo "<div id='source'><p style='color:red';>PathfinderID already exists</div>";
}
else
{
//Insert in to Devices Table
$tsql="INSERT INTO devices (pathfinderid, locationid, addeddate, status, creation_date, status_note) VALUES (?,?,?,?,?,?)";
$var = array ($pathfinderid, $locationid, $date, $status, $date, $statusnote);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Insert in to Movment Log
$tsql="INSERT INTO movement_log (pathfinderid, locationid, status, update_timestamp, addeddate, status_note) VALUES (?, ?, ?, ?, ?, ?')";
$var = array ($pathfinderid, $locationid, $status, $date, $date, $statusnote);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Display the confirmation messgae
echo "<div id='source'><p style='color:green;'>Device Added</p></div>";
}
}
}
}
?>
The error is flagging as beng on line 52 which is:
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
Any ideas? The only thing I can think is if it is because I am reusing variable names?
You've got a double variable ($statusnote)
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
should be
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}

Add try to pdo execute

Code below adds data in db
$sth = $this->db->prepare('UPDATE `adwords_clients_google` set status = 2');
$sth->execute();
$sth = null;
$sth = $this->db->prepare('
INSERT INTO
`adwords_clients_google`
(`client_foreign_id`, `status`, `client_name`, `client_currency`)
VALUES
(:id, 1, :name, :currency)
ON DUPLICATE KEY UPDATE
`status` = VALUES(`status`),
`client_name` = VALUES(`client_name`),
`client_currency` = VALUES(`client_currency`)
');
$sth->bindParam(':id', $id);
$sth->bindParam(':name', $name);
$sth->bindParam(':currency', $currency);
foreach($accounts as $account) {
$id = $account->customerId;
$name = $account->name;
$currency = $account->currencyCode;
$sth->execute();
}
and I would like to add try here, something like
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (Exception $ex) {
helper::putToLog($sth->debugDumpParams(), true);
helper::putToLog("ERROR: ".$ex->getMessage(), true);
}
but i don't know should I add it for every row? How can I do that?
If you are using PDO for connecting DB then use PDOException class to handle the exception.
try {
if ($sth->execute()) {
helper::putToLog('ok queryCampaignArr, inserted rows: ' . $sth->rowCount());
} else {
helper::putToLog('not ok', true);
}
} catch (PDOException $ex) {
$Exception->getMessage(); // Error message
(int)$Exception->getCode(); // Error Code
}

Why is on a occasion, only part of a record inserted?

The problem I am having is on occasion (1 of every 8 or so) insertions to the database, the string value of (fileLocation) will be incomplete. so for example..
what should be "filecomplete.mp4" will be inserted as "filecomple".
Has anyone experienced this before or have any ideas as to what the problem could be?
Here is my insert statement.
public function addNewGame($gameID, $receiverID, $senderID, $gameTrack, $fileLocation){
$this->gameid = $gameID;
$this->receiverid = $receiverID;
$this->senderid = $senderID;
$this->gameTrack = $gameTrack;
$this->filelocation = $fileLocation;
$SQUERY = "SELECT GameId FROM ActiveGames WHERE GameId = :gameid";
try{
$stamt = $this->connection->prepare($SQUERY);
if ($stamt === false) {
throw new Exception($this->connection->error);
}
$stamt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stamt->execute();
$result = $stamt->fetchAll();
$resultCount = count($result);
if($resultCount > 0){
echo "existing record";
} else{
$QUERY = "INSERT INTO ActiveGames (GameId,
ReceiverId,
SenderId,
GameTrack,
FileLocation)
VALUES (
:gameid,
:receiverid,
:senderid,
:gametrack,
:filelocation)";
try{
$stmt = $this->connection->prepare($QUERY);
if ($stmt === false) {
throw new Exception($this->connection->error);
}
$stmt->bindValue(':gameid', $this->gameid, PDO::PARAM_INT);
$stmt->bindValue(':receiverid', $this->receiverid, PDO::PARAM_INT);
$stmt->bindValue(':senderid', $this->senderid, PDO::PARAM_INT);
$stmt->bindValue(':gametrack', $this->gameTrack, PDO::PARAM_STR);
$stmt->bindValue(':filelocation', $this->filelocation, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
}
catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}

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;
}
}
?>

Categories