PDO - Insertion (INSERT INTO...) code doesn't work - php

I'm trying to insert the current date/time to the database as the last time the user logged in. For some reason this doesn't work.
Other insertion scripts running on the very same page work well, and the connection is ok.
I use the same syntax to insert other stuff throughout the whole site, so I don't get what's wrong.
I can guarantee that the else part is being executed when I'm entering my password.
Here's the piece of code I am talking about.
if(!$pwVer){
// code to execute if the password is incorrect.
} else {
$dateT = date("Y-m-d H:i:s");
$up_date = $con->prepare("INSERT INTO tbl_user_test (user_last_login) VALUES (:l_login)");
$up_date->bindParam(':l_login', $dateT);
$up_date->execute();
validateUser($userid); //sets the session data for this user
header("Location: cart.php");
$con = null;
die();
}
Some background:
$pwVer returns `true` if the password is correct.
both `tbl_user_test` and `user_last_login` are written exactly as they're in the database.
Thanks in advance!

I'm trying to insert the current date/time to the database as the last time the user logged in. For some reason this doesn't work.
There is no error visible in your code, so it should be executed. One possible problem could be that PDO is in silent mode, which doesn't tell you what or if an error has occured. Set PDO to fail with an exception.
Also, there's no need to construct the current date yourself; you can use SQL's NOW().
<?php
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try {
$up_date = $con->prepare("INSERT INTO tbl_user_test (user_last_login) VALUES (NOW());");
$up_date->execute();
}
catch( Exception $e ) {
echo $e; exit;
}
header("Location: cart.php");
$con = null;
die();

Did you try NOW() for the current date time ?

Once check with this
$up_date->bindParam(':l_login', $dateT, PDO::PARAM_STR);

Related

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

PHP exception handling after SQL insert [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I am creating a very simple registration form in php, currently when the user tries to register there will popup a javascript alert with a succes or fail message.
Now I want to catch the sql exception to show if the username or email already excists in the database instead of a standard fail message.
This is the code I have so far:
if(isset($_POST['btn-signup']))
{
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
if(mysql_query("INSERT INTO user(username,password,email) VALUES('$uname','$upass','$email')"))
{
?>
<script>alert('successfully registered ');</script>
<?php
}
else{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
?>
How can I check if the email or username already excists in the database? Both variable's are already unique in the database.
From Comments:
I don't want 2 queries while the database can return an exception for me. If there are about 10 million records in that table, I don't want to check them all before inserting a new one.
Ok, so you have one query to insert and check is unique? So you have to INSERT on a UNIQUE_INDEX MySQL column, you can catch these sort of exceptions with the following style of answer shameless stolen from this answer to this question:
In the case of this answer we'll assume you're using PDO, because you should. Please read up about it.
// Pre-setup the database connection somewhere, usually an include (or a class)
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
// PDO needs to be set in Exception mode:
$link->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Input Processing functions.
// (entirely optional)
$uname = MyCleanerFunction($_POST['uname']);
$email = MyCleanerFunction($_POST['email']);
//please see note below re:MD5
//$upass = md5($_POST['pass']);
$options['cost'] = 12;
$upass = password_hash($_POST['pass'],PASSWORD_BCRYPT,$options);
//now reach the code part:
try {
//PDO query execution goes here:
$statement = $link->prepare("INSERT INTO user(username,password,email) VALUES(:uname, :email, :pass)"));
$statement->bindValue(":uname", $uname);
$statement->bindValue(":email", $email);
$statement->bindValue(":pass", $upass);
$statement->execute();
//reaching here everything is ok!
}
catch (\PDOException $e) {
if ($e->errorInfo[1] == 1062) {
// The INSERT query failed due to a key constraint violation.
// THIS means that it failed because the Primary Key
// (the email) appears already in the database table.
}
if($e->errorInfo[1] == 9999){
// possible other IF clauses for other errors in INSERT.
}
}
You would also do well to read up about catching and outputting PDO errors. As well as all about MySQL Unique Key Constraints.
Also very useful alternative viewpoint that you Should not catch PDO exceptions.
Also please note that MD5 is an extremely weak hash for storing passwords and that PHP password_hash function is the much preferred way of doing it.
PLEASE use Prepared Statements for your MySQL interactions, the layout above is a rough guide to how they look and is very similar for MySQLi and PDO. Prepared Statements go a long way towards securing your data from malicious user input.
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT COUNT(*) FROM persons WHERE Email = '$_POST[eMailTxt]'";
if (mysqli_query($con,$check)>=1)
{
echo "User Already in Exists<br/>";
}
else
{
$newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
if (mysqli_query($con,$newUser))
{
echo "You are now registered<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}

how to insert PHPSESSID into db with PDO?

I am trying to insert $_COOKIE['PHPSESSID'] in db with pdo, but i am having issue, can somebody help out?
here is the db table design : db table name: unregistered_customer_orders
session_id (int)
sel_article_id (varchar, 32)
sel_article_qty(smallint)
sel_article_color(varchar)
sel_article_size(varchar)
order_date(datetime)
HERE IS THE CODE
session_start();
try {
include_once'../includes/connect.inc.php';
$q ="INSERT INTO unregistered_customer_orders SET
session_id = $_COOKIE['PHPSESSID'] ,
sel_article_id = :sel_article_id,
sel_article_qty =:sel_article_qty,
sel_article_color = :sel_article_color,
sel_article_size = :sel_article_size,
order_date = NOW()";
$stm = $pdo->prepare($q);
$stm->bindValue(':sel_article_id', $sel_article_id);
$stm->bindValue(':sel_article_qty', $sel_article_qty);
$stm->bindValue(':sel_article_color', $sel_article_color);
$stm->bindValue(':sel_article_size', $sel_article_size);
$stm->execute();
if ($stm) {
echo "Insert";
exit();
}
else{
echo "Insert failed";
exit();
}
} catch (PDOException $e) {
echo "sth got wrong with the insert".$e->getMessage();
}
Your code has a serious SQL injection problem!
You inject unescaped SQL code into the query - or at least are trying to do so, from the cookie.
The cookie variable should go into the bindValue part just like everything else. Create a new variable name that goes into the prepared statement part, and bind the cookie value to it.
Note that PHP can be configured to use a different name for the session cookie! You don't have to access the $_COOKIE variable after you started the session, you can simply call the session_id() function to get the currently used session id.
Before using session_start(), the configured cookie name can be read by calling session_name(). Don't hardcode the cookie name into your code - it will create hard to debug errors when a new server has a different configuration.

php mysqli FRUSTRATION

I have to following code:
session_start();
if(isset($_SESSION['Username']))
{
//User has selected auto sign-in re-fill session variables.
$mysqli = new mysqli('****','****','****','****');
if($mysqli->errno)
{
//Error connecting
}
else
{
//No error connecting to database
$stmt = $mysqli->prepare("SELECT Expires FROM Subscribers WHERE UName=?");
$stmt->bind_param('s', $_SESSION['Username']);
$stmt->execute();
$stmt->bind_result($Expires);
$stmt->store_result();
while($row = $stmt->fetch())
{
if($Expires < time())
{
//Deny user
$pageToShow = "Payment";
}
else
{
//Accept
$pageToShow = "Content";
}
}
}
}
else
{ ... }
I am getting the error Fatal error: Call to a member function bind_param() on a non-object in /home/content/42/7401242/html/****/wp-content/themes/****/archive.php on line 15
I just had an error like this about 30min ago on a different page, and I had for gotten the FROM from the sql query, but I have read, re-read, re-checked, every single letter of the code, over and over. I am about to pull all of my hair out...
What am I doing wrong?
That's simple.
You're not handling errors.
And not even asking how to do that.
In your other question they showed you error itself instead of showing you the way how can you see the error yourself.
In the present question the answer is "check your query" which is not too helpful too.
Instead of asking other people to find typos in your queries, you have to ask mysqli to do that. That's way more efficient, especially because there could be another mistake, not in the query but somewhere else.
So, you have to check every database interaction result and translate it into PHP error.
$sql = "SELECT Expires FROM Subscribers WHERE UName=?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error);
...
$stmt->execute() or trigger_error($mysqli->error);
so, you will immediately know what's going wrong.
The error tells you that your SQL query is returning an empty result.
two things you must do:
check that you are connected to the database properly and that you
have the permissions to access the data in the database
check your query and see if it returns any results in your SQL
database.

PHP and MySQL using the PDO class

I am trying to update a database, here is my code
if (isset($_GET['placeorder']))
{
include 'includes/db.php';
try
{
$newBalance = $_POST['balance'] + $_POST['oldbalance'];
$sql = 'UPDATE customer SET
balance = :balance
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':balance', $newBalance);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Could not add the new balance for the customer' . $e->getMessage();
include 'result.php';
exit();
}
header('Location: .');
exit();
What I am trying to do is update the balance for a customer that is coming from a form that was submitted. I am able to get the value in the code all the way up to where I get to $s->execute(); if I try to echo the value, which is $newBalance, it will not show after that line is executed, the page goes blank. Something is happening in the execute statement. $s->execute() that it does not allow my code to proceed. Any idea? Am I using the PDO class the wrong way. It is not getting to the "catch" statement. Any help would be great. The end result is that the page returns to where it started with the updated balance.
You are only binding a value to the balance, not the id, you need a line like:
$s->bindValue(':id', $id);
It would be a good idea to make sure that $_POST['balance'] and $_POST['oldbalance'] are set as well before using them in your query:
$balance = isset($_POST['balance'])? $_POST['balance'] : 0;
$oldbalance = isset($_POST['oldbalance'])? $_POST['oldbalance'] : 0;
$newbalance = $balance + $oldbalance;
If you aren't getting an error, you likely don't have error reporting on, you can enable it by adding error_reporting(E_ALL); to the top of your page.
var_dump() both variables $_POST['balance'] & $_POST['oldbalance']. I am sure they are coming as string. Type casting is one of the solution. Try typecasting in this case to perform addition on int/float.
$newBalance = (int)$_POST['balance'] + (int)$_POST['oldbalance'];

Categories