Check if date is in database and is greater than [duplicate] - php

This question already has answers here:
MySQL date comparison
(7 answers)
Closed 5 years ago.
I have date type input on my site. I want to check if selected date is in the database and also is greater than for example 2017-01-01. I have something like this. How to do that?
if(ISSET($_POST['receipt_date'])) {
$receipt_code=$_POST['receipt_date'];
$checkdata="SELECT receipt_date FROM receipts WHERE receipt_code='$receipt_code' ";
$query=mysql_query($checkdata);
if(mysql_num_rows($query)>0) {
echo "exist";
} else {
echo "ok";
}
exit();
}

Check this snippet :
<?php
$link_to_db = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if(isset($_POST['receipt_date']))
{
$receipt_date = $_POST['receipt_date'];
$recept_datetime = new Datetime($receipt_date); # use \ before it if you using namespaces
$check_data = "SELECT receipt_date FROM receipts WHERE receipt_date = '".$recept_datetime->format('Y-m-d H:i:s')."'";
$query = mysqli_query($link_to_db, $checkdata); # use mysqli instead of mysql functions
if(mysqli_num_rows($query) == 0) {
echo "ok";
}
$check_datetime = new Datetime('2017-01-01 00:00:00');
# work only on php > 5.2.2
if ($receipt_datetime > $check_datetime) {
echo "check OK";
}
}
?>
Hope this helps !

Related

why data cannot post to database? [duplicate]

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
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm trying to insert data into the database, it run my coding and i get output as 'SOP data Added Successfully', but the data does not get into the database.
if (isset($_SESSION['admin_id']))
{
include 'databaseConnection.php';
if (isset($_POST['add_btn']))
{
$sop_name = $_POST['sop_name'];
$sop_step = $_POST['sop_step'];
$sop_comment = $_POST['sop_comment'];
$department_id = $_POST['department_id'];
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM sop WHERE sop_name = '$sop_name' && admin_id = '".$_SESSION['admin_id']."'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
if ($count == 1)
{
echo '<script language="javascript">';
echo 'alert("SOP Data Already Existed")';
echo '</script>';
}
else
{
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
echo '<script language="javascript">';
echo "alert('SOP Data Added Succesfully'); window.location.href='dashboardOrganizationDepartment.php'";
echo '</script>';
}
}
?>
I expect that the result can be post into the database, but it is not. There is also not showing any errors for me to refer.
Can you put some try catch within your insert query, you will get the actual error in query
try {
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
} catch (Exception $e) {
die($e->getMessage());
}

Don't show any data data [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
Here is my php and mysql code. It don't show any data . please tell me where is my error:
<?php
$ddaa = mysql_query("SELECT ref FROM users WHERE id='$uid'");
$mallu2 = mysql_query("SELECT mallu FROM users WHERE id='$ddaa'");
$result = mysql_fetch_array($mallu2);
echo $result['mallu'];
?>
You can use Mysqli,mysql is deprecated
a little example:
conection to db test
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'test');
if ($mysqli->connect_errno) {
echo "Error: Errot on connection : \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
}
// the query
$sql = "SELECT ref FROM users WHERE id=$uid";
//if don't have result
if ($resultado->num_rows === 0) {
echo "we can't find data with $uid. try again !.";
exit;
}
//print the result
while ($dato = $resultado->fetch_assoc()) {
echo $dato['ref'];
}
Mysqli Php documentation

if empty query show messages in php [duplicate]

This question already has answers here:
How do I check db query returned results using PHP's PDO
(3 answers)
Closed 6 years ago.
I need little help with my code.
I want to show message when table is empty.
My code is
function category()
{
global $config,$db,$lang;
$result = "SELECT id, name FROM category ORDER BY id";
$stmt = $db->prepare($result);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$tpl=parse_tpl('category.php');
$tpl=str_replace("{_HTTP_SERVER_}",$config['http_server'],$tpl);
$tpl=str_replace("{cat_id}",$row['id'],$tpl);
$tpl=str_replace("{cat_title}",kill_tags($row['name']),$tpl);
echo $tpl;
}
if(empty($row)) echo $lang['category_not'];
}
When no records in table show this message
$lang['category_not']
I tried with if(empty($row)) , if (!$row) and if($row == o) but didn't work.
You have to use your code as following way:
if($stmt->rowCount() == 0)
{
echo "nothing found message";
}
else
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC)
{
// code for loop
}
}// else ends here

Sharing variables between functions [duplicate]

This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 8 years ago.
I need to display different verbiage according what the user's status is. I realize the while() variables are out of scope to Online_Status() but I cannot figure out how to share the variables or even define new variables in Online_Status() contianing the same information as while(). I've tried putting Online_Status() in while(), around while(), outside of while() and every other configuration for hours. Not happening. I would appreciate any help!
<?php
require_once('connect.php');
$con = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die('Connection failed: ' . mysqli_connect_error());
$sql = mysqli_query($con, "SELECT UserType, Online, InChat FROM membership WHERE UserType = 2 ORDER BY Online DESC");
while($row = mysqli_fetch_array($sql)){
$UserType = $row['UserType'];
$Online = $row['Online'];
$InChat = $row['InChat'];
echo Online_Status();
}
function Online_Status(){
if ($Online == 0) {
echo "I am not online. Please come back later";
}
else if($Online == 1 && $InChat == 0){
echo "I am Online and I will be in my chatroom shortly.";
}
else if($Online == 1 && $InChat == 1){
echo "I am Online chat with me now!";
}
}
mysqli_close($con);
?>
Use global keyword:
function Online_Status(){
global $Online;
if ($Online == 0) {
echo "I am not online. Please come back later";
}
}
It is better to pass variables through a function via function parameters:
function Online_Status($Online){
if ($Online == 0) {
echo "I am not online. Please come back later";
}
}
And call it:
Online_Status($Online);
And also, take a look at PHP's Variable Scope.

Best way to check for existing user in mySQL database? [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.

Categories