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()){
Related
I went through this login system with multi-users. It's working fine since it doesn't allow my status_id users '2' to login (inactive status), but when this happens I get the echo message twice on screen.
What am I doing wrong?
I want to validate both user/password, user_type (admin/user) and user_status (1-active, 2-inactive).
<?php
include 'database/connect.php';
if (isset($_POST["submit"])) {
$email = $_POST["txtemail"];
$pass = $_POST["txtpass"];
$query = mysqli_query($con, "SELECT user_email,user_password,user_type_id, status_id FROM user");
while ($row = mysqli_fetch_array($query)) {
$db_email = $row["user_email"];
$db_pass = $row["user_password"];
$db_type = $row["user_type_id"];
$db_user_status = $row['status_id'];
if ($email == $db_email && $pass == $db_pass && $db_user_status == '1') {
session_start();
$_SESSION["email"] = $db_email;
$_SESSION["type"] = $db_type;
if ($_SESSION["type"] == '1') {
header("Location:admin/home_admin.php");
} else {
header("Location:user/home_user.php");
}
} else {
echo "Ups. Algo de errado aconteceu.";
}
}
}
Looking at your code, if the conditions specified inside the loop fails then the else will execute.
So if your user table holds 3 records and all 3 records doesn't satisfy the condition specified it will execute else statement and 3 times.
This might be the reason.
Well it looks like you are looping through every user inside your user table, so the posted email and password can only be right for one user and for the rest of them your program will go through the else statement
<?php
include 'check_login.php';
if(isset($_POST['apply']))
session_start();
$uid = $_SESSION['user_index'];
$leavetype = $_POST['leavetype'];
$fromdate = $_POST['fromdate'];
$todate = $_POST['todate'];
$description = $_POST['description'];
$status=0;
$isread=0;
if($fromdate > $todate){
$error=" ToDate should be greater than FromDate ";
}
include '../db_config/connection.php';
$sql = "SELECT * FROM user_info where user_index = '$uid'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$uid = $row['user_index'];
header("location:../add_leave.php?msg=Leave for $uid is not available&ent_id=$uid");
}
} else {
include '../db_config/connection.php';
$sql = "INSERT INTO tblleaves(leavetype, todate, fromdate, description, status, isRead, user_index)
VALUES ('$leavetype', '$fromdate', '$todate', '$description', '$status', '$isread', '$uid')";
if($conn->query($sql) === TRUE) {
header("location: apply_leave.php?message=$leavetype have been requested");
} else {
$error = $conn->error;
header("location: add_leave.php?err=$error");
}
$conn->close();
}
$conn->close();
?>
I've been working on a Leave management and on the User side the user needs to apply for a leave but I am unable to get the ID of the current logged in user to be added to another table called tblleaves the table where the user id resides is user_info. I can add other data to tblleaves but not the user id.
You need to reorganize this script and you aren't checking things properly. You also have an SQL injection issue:
<?php
# Add this to the top, don't add it as an "if" conditional
session_start();
# Add this once and also at the top, regardless of if you use it
include('../db_config/connection.php');
# Same
include('check_login.php');
# I would make a function for this (move to it's own page and include it)
function getUserInfo($uid,$conn)
{
$uid = (is_numeric($uid))? $uid : false;
if(!$uid)
return false;
# Fetch
$result = $conn->query("SELECT * FROM user_info where user_index = '$uid'");
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row;
}
return [];
}
# Create a function to add the user's leave BUT YOU NEED TO BIND PARAMETERS
# HERE! WHAT YOU HAVE IS NOT SAFE!!
function addUserLeave($uid,$array,$conn)
{
# Question marks are placeholders for values
$sql = "INSERT INTO tblleaves(leavetype, todate, fromdate, description, status, isRead, user_index) VALUES (?,?,?,?,1,1,?)";
# Prepare the statement
$query = $conn->prepare($sql);
# Bind the values to question marks in the statement, use the first parameter in this
# method to indicate to the method what each value type each should be
$query->bind_param('ssssssi',$array['leavetype'], $array['fromdate'], $array['todate'], $array['description'],$uid);
# Now run the query
return $query->execute($sql);
}
# Set a default error
$error = 'You must submit the form';
# You have to use braces to cover all the other assigned post values
if(isset($_POST['apply'])) {
$uid = $_SESSION['user_index'];
$leavetype = $_POST['leavetype'];
$fromdate = $_POST['fromdate'];
$todate = $_POST['todate'];
$description = $_POST['description'];
# I have no idea how these are used, they seem pointless based
# on your sample script
$status =
$isread = 0;
# Check date
if($fromdate > $todate) {
$error = '"To" date should be greater than the "from" date';
}
# If you have an error on date, it doesn't make sense to keep going
# with the script, so use else
else {
# Fetch user info here
$userInfo = getUserInfo($uid,$conn);
# Check that there is a value here
if(!empty($userInfo['user_index'])) {
# Redirect AND exit
header("Location: ../add_leave.php?err=Leave for {$uid} is not available&ent_id={$uid}");
exit;
}
else {
# Run the function to insert
$added = addUserLeave($uid,$_POST,$conn);
if($added) {
# Redirect AND exit
header("Location: apply_leave.php?message={$leavetype} have been requested");
exit;
}
else
$error = $conn->error;
}
}
}
# Default is to redirect
header("location: add_leave.php?err={$error}");
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.
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.
I am creating a login part to my web page. When a new person registers their details, pressing the register button goes to a register_ok part, showing below:
case 'register_ok':
if (!$_POST['client_username'] || !$_POST['client_password'] ||
!$_POST['client_email']) {
die('You did not fill in a required field.');
}
// check if username exists in database.
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
die('Sorry, the username: <strong>'.$_POST['client_username'].'</strong>'
. ' is already taken, please pick another one.');
}
}
// check e-mail format
if (!preg_match("/.*#.*..*/", $_POST['client_email']) ||
preg_match("/(<|>)/", $_POST['client_email'])) {
die('Invalid e-mail address.');
}
// no HTML tags in username, website, location, password
$_POST['client_username'] = strip_tags($_POST['client_username']);
$_POST['client_password'] = strip_tags($_POST['client_password']);
// now we can add them to the database.
// encrypt password
$_POST['client_password'] = md5($_POST['client_password']);
if (!get_magic_quotes_gpc()) {
$_POST['client_password'] = addslashes($_POST['client_password']);
$_POST['client_email'] = addslashes($_POST['client_email']);
}
$insert = "INSERT INTO client (
client_username,
client_password,
client_name,
client_email,
client_last_access)
VALUES (
'".$_POST['client_username']."',
'".$_POST['client_password']."',
'".$_POST['client_name']."',
'".$_POST['client_email']."',
'now()'
)";
if(!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else{
$id= mysql_insert_id();
session_start();
echo '<script>alert("You May Now Login");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
break;
}
When I register a new person, I get the following error:
Error: Query was empty
Why is this?
In the line if(!mysql_query($sql,$con)) {, do you mean $insert instead of $sql?
Do:
if(!mysql_query($sql,$con)) {
to
if(!mysql_query($insert,$con)) {
your variable name is not correct