On refresh, values keep adding in drop down - php

Code:
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
$_SESSION['ids'][] = "";
$query = mysqli_query($this->connection, "SELECT EmployeeId from employees where EmployeeId NOT IN(Select EmployeeId from employeeprofile)") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array.
$_SESSION['ids'][] = $row["EmployeeId"];
}
}
Values are coming from database and whenever I refresh duplicate values are added. I don't know what to do.

That's because every time you refresh the page, (probably with every getEmployeeId() method call) SQL query gets executed and employee ids gets appended to $_SESSION['ids'] array. You need to encapsulate that block of code inside an if block.
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
exit();
}
if(!isset($_SESSION['ids']) && count($_SESSION['ids']) == 0){
$_SESSION['ids'][] = "";
$query = mysqli_query($this->connection, "SELECT EmployeeId from employees where EmployeeId NOT IN(Select EmployeeId from employeeprofile)") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
$_SESSION['ids'][] = $row["EmployeeId"];
}
}
}
Sidenote: You need to add exit(); after header(...); statement, because header(...); alone itself is not sufficient to redirect the user to a different page.

Related

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

Trying to get property of non-object - PHP

So I'm trying to get the teacher_id that is corresponding to the teacher's first and last name that the user has entered, but when I try to get the teacher_id it outputs Trying to get property of non-object. Does anyone have any ideas?
PHP
<?php
// PROCESSES STUDENT INFO
// get connect page
require '../../connect.php';
// get input info
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$teacher_first_name = $_POST['teacher_first_name'];
$teacher_last_name = $_POST['teacher_last_name'];
// check if input is not empy
if(!empty($student_id) && !empty($first_name) && !empty($last_name) && !empty($teacher_first_name) && !empty($teacher_last_name)) {
// check if numeric inputs have a number
if(is_numeric($student_id)) {
$teacher_check = mysqli_query($link, "SELECT teacher_id FROM teachers WHERE first_name='$teacher_first_name' AND last_name='$teacher_last_name'");
// check if teacher exists
if($teacher_check) {
$row = $teacher_check->fetch_object();
$result = mysqli_query($link, "INSERT INTO students (student_id, first_name, last_name, teacher_id) VALUES ($student_id, '$first_name','$last_name', $row->teacher_id)");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
echo mysqli_error($link);
// header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=Teacher Does Not Exist");
}
} else {
header("Location: ../../../admin.php?message=Please add a number for Student ID");
}
} else if (empty($student_id) || empty($first_name) || empty($last_name)) {
header("Location: ../../../admin.php?message=Please add you're input values");
}
?>
change this line, you are checking whether the query is ok but you have not checked whether it has any results.
if($teacher_check) {
$row = $teacher_check->fetch_object();
to (this line checks whether you have any result data if you have result data you have it $row otherwise null)
if($row = $teacher_check->fetch_object()){

get no results for query. its not true,not false and to null

i did some query to check username and password.
when i enter the right data its working ok,
if i put the right email and wrong password its working ok,
when i put a username that do not exist i get no results and white screen. now echo command jump. its looks like its stuck and there is no error.
any idears?
if (isset($email) && isset($password)) {
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE user_email = '{$email}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row["user_password"] == $password) {
echo json_encode($row);
} else {
echo ('{"user_id":"0","user_name":"","user_email":"","user_password":"","register_date":"2016-03-05","confirm":"0"}');
}
}
} else {
echo("error");
}
} else {
echo($result);
echo("Missing Vars");
}
I bet that "if ($result)" is true but it never enters the while loop since there are no rows to iterate over. This would lead to a blank screen. Try echoing out what is returned from the database and echoing out each nest to see what gets output. Like the following:
if ($result) {
echo("if $result must be true because I made it in");
while ($row = mysqli_fetch_assoc($result)) {
echo("I made it in the while loop if there are rows in my result");
if {
echo("I made it in while's if");
...
} else {
echo("I made it in while's else");
...
}
}
} else {
echo("if $result must be false because I didn't make it in");
echo("error");
}
I bet that using the above example you'll see:
if $result must be true because I made it in
And that is all you'll see

PHP If statement returning early(amateur)

I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";

how to prevent same record to be inserted twice in mysql using php

The following is my code that I have written for not inserting same data
I would like if the record exist in mysql then it should show me error message that the record already exist the else part should insert record to database but it not working
can any one help me plz
the help would be highly appreciated
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you did mistake here.
$check="SELECT * FROM contacts WHERE office_name = '$officeName'";
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
just add mysql_query like
$check=mysql_query("SELECT * FROM contacts WHERE office_name = '$officeName'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}
or you can also use like
$name=$_POST['username'];
$q="select * from login where name='$name' ";
$rs=mysql_query($q);
if(mysql_fetch_row($rs)>0)
{
echo "already exist";
}
else
{
$msg="done";
}
Add the ON Duplicate KEY Update. This way you don't need to check if the record already exists, which means you don't need an extra select query just to check. If it exists, nothing happens.
INSERT INTO contacts (office_name, contact_no, digital_no, mobile_no)
VALUES ('$contactName','$contactNo','$digitalNo','$mobileNo')
ON DUPLICATE KEY UPDATE office_name = office_name
And set the office_name to be the primary key or a unique index.
There is missing one step, your first query is not executed, please try this:-
function addcontact()
{
if(isset($_POST['addContact']))
{
$officeName = strip_tags($_POST['office_name']);
$contactName = strip_tags($_POST['contactName']);
$contactNo = strip_tags($_POST['contactNo']);
$digitalNo = strip_tags($_POST['digitalNo']);
$mobileNo = strip_tags($_POST['mobileNo']);
$check= mysql_query("SELECT * FROM contacts WHERE office_name = '{$officeName}'");
if(mysql_num_rows($check) != 0)
{
echo "Already in Exists<br/>";
}else
{
$sql = mysql_query("INSERT INTO contacts (office_name, contact_no,
digital_no, mobile_no) VALUES
('$contactName','$contactNo','$digitalNo','$mobileNo')") or die(mysql_error());
if($sql)
{
header("Location: index.php?admin&done"); exit;
}
else
{
header("Location: index.php?admin&failed"); exit;
}
}
}
}
you can handle it from database side. write a stored procedure such a way that first check weather the record is in database or not if exist then ignore it and get back the text "Record already exist", if not exist then insert it to table. use conditional statements in mysql.

Categories