I am trying to check if the value of variable is equal to 0 but if condition is not working correctly. Please see the following code
if(isset($_GET['empid']))
{
$sql_query="SELECT accept leave_mgt WHERE empid=".$_GET['empid'];
$result_set=mysqli_query($conn, $sql_query);
if(isset($sql_query))
{
$sql="UPDATE leave_mgt SET accept='1'where empid=".$_GET['empid'];
$result=mysqli_query($conn,$sql);
if($result)
{
echo "test";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else
{
$sql="UPDATE leave_mgt SET accept='0'where empid=".$_GET['empid'];
$result=mysqli_query($conn,$sql);
if($result)
echo "testing";
else
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Line 16
if(sizeof($result_set->fetch_assoc()) < 1) {
Related
This is the code I'm using for deleting row from my DB:
<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";
if ($con->query($query)==TRUE)
{
echo " record deleted";
}
else
{
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
?>
The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.
Why is this happening? how can I verify that my record has been deleted from my DB?
You can use mysqli.affected-rows.
Consider the following:
$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
echo " record deleted";
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
I've built a php login that verifies the user and redirects then to landing.php if successful. Otherwise, the login error is given to the user. Once on landing.php, I am trying to check that $_SESSION exists. If it does, then use a piece of it. If it doesn't it should redirect the user to the login page. However, if I directly type the landing.php url in the browser to skip the login, the page never redirects even though the $_SESSION is empty. Please advise to the best way to check the session.
MY CODE:
landing.php: (PHP Script)
<?php
session_start();
include('inc.php');
if (!(session_id())) {
header("Location: ['url']/index.php"); /*url not displayed for security*/
} else {
$welcome = "Welcome ".$_SESSION['userinfo']['firstname'];
}
?>
login.php: (Where session is created)
<?php
session_start();
include("inc.php");
if ((isset($_POST['username'])) and (isset($_POST['password']))) {
$login = $_POST['username'];
$pass = $_POST['password'];
} else {
//echo json_encode("Credentials did not save. Please try again.");
echo "Credentials did not save. Please try again.";
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno) {
//echo json_encode("There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error);
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
//echo json_encode("There was a problem connecting to MySQL.");
}
$sql = "SELECT * FROM sched_users WHERE login = ? ORDER BY login LIMIT 1";
if (!($sql = $conn->prepare("SELECT * FROM sched_users WHERE login = ? ORDER BY login LIMIT 1"))) {
//echo json_encode("Prepare failed: (" . $conn->errno . ") " . $conn->error);
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
//echo json_encode("Prepare failed.");
}
if (!($sql->bind_param("s", $login))) {
//echo json_encode("Binding parameters failed: (" . $sql->errno . ") " . $sql->error);
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
//echo json_encode("Binding parameters failed.");
}
if (!$sql->execute()) {
//echo json_encode("Execute failed: (" . $sql->errno . ") " . $sql->error);
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
//echo json_encode("Execute failed.");
}
$res = $sql->get_result();
if ($res->num_rows === 0) {
//echo json_encode("No user record found.");
echo "No user record found.";
} else if (!(($res->num_rows === 1) or ($res->num_rows === 0))) {
//echo json_encode("Too many results returned.");
echo "Too many results returned.";
} else {
$row = $res->fetch_array();
$hash = $row['password'];
if (password_verify($pass, $hash)) {
/*
$session = true;
echo json_encode($session);
*/
$_SESSION['userinfo']['firstname'] = $row['firstname'];
$_SESSION['userinfo']['lastname'] = $row['lastname'];
$_SESSION['userinfo']['email'] = $row['email'];
$_SESSION['userinfo']['phone'] = $row['phone'];
$_SESSION['userinfo']['company'] = $row['company'];
$_SESSION['userinfo']['department'] = $row['department'];
$_SESSION['userinfo']['admin'] = $row['admin'];
$_SESSION['userinfo']['statusflag'] = $row['statusflag'];
$_SESSION['userinfo']['revoked'] = $row['revoked'];
header("location: [url]/landing.php");/*url not displayed for security*/
} else {
//$session = false;
//echo json_encode($session);
//echo json_encode("The username or password does not match. Please try again.");
echo "The username or password does not match. Please try again.";
}
}
$sql->close();
$conn->close();
?>
This is your problem:
session_start();
...
if (!(session_id())) {
As soon as you start your session, you will have a session ID so the condition !(session_id() will always be false.
You should check for the content of the session instead, for example:
if (!array_key_exists('userinfo', $_SESSION)) {
...
In my PHP code, i'm easily writing records to my database but for some reason i can't read anythign out. My PHP code is:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
if ($conn->query($sql) === TRUE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO companies (name)
VALUES ('mycompany')";
if ($conn->query($sql) === TRUE)
{
echo "insert success";
}
else
{
echo "insert failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
The output I get from the browser when i run it is:
query failureError: SELECT * FROM companies
insert success
I've tried variations of apostrophes, carets, quotes in that $sql string. I've tried running this query in HeidiSQL and it works fine. Any ideas where I'm going wrong? Any suggestions of more basic stuff I can try to narrow down the source of the problem?
thanks!
Using mysqli->query() with a SELECT statement returns an instance of mysqli_result. It is not identical to true (=== true), but nor does it represent an error.
Moreover, $result is undefined.
Use this instead:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
if (($result = $conn->query($sql)) !== FALSE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
...
This simply changes your === TRUE check to !== FALSE. MySQLi::query() returns boolean FALSE on failure, boolean TRUE on a successful query without result sets or a mysqli_result upon success with a result set.
This also assigns the result of query() into $result.
You have not assign the query result to $result variable.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
$result = $conn->query($sql);
if ($result === TRUE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO companies (name)
VALUES ('mycompany')";
if ($conn->query($sql) === TRUE)
{
echo "insert success";
}
else
{
echo "insert failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
The problem is that a SELECT query will return a mysqli_result object on SUCCESS not a boolean TRUE. Only if the query fails, will it return a boolean FALSE;
Therefore you should use it like this :
$result = $conn->query($sql);
if ($result !== FALSE){
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
just change your if condition :-
if ($result = $conn->query($sql))
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
}
I am new to php and SQL and just toying around with a project for my own understanding of accessing, updating and deleting data from my Database.
I have managed to show the selected data, create a button to delete a specific Id but really needing some assistance with deleting the selected row or record instead of hard coding in the ID in my delete php script.
Here is an example of my script:
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is the delete.php
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='6' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
what I would like it to do is, delete the row from which you hit the delete button from and not just delete the row I have specified in the delete.php script. I understand HOW it should work by posting the id but not sure how to do it.
Do like this
<?php
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
<?php
$sql = "SELECT id, firstname, lastname, joinDate FROM customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span><a href='deleteMember.php?id=".$row['id']."'>Delete</a></span>" .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
in place of your form use this
DELETE
and in your delete query must be like below
$sql = "DELETE FROM customers WHERE id='".$_GET['id']."' ";
or stay in your post form with:
while($row = $result->fetch_assoc()) {
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<form action='deleteMember.php' method='POST'>
<input type='hidden' name='myid' value='".$row['id']."' />
<button type='submit'>Delete</button>
</form>
</span>" . " " .
"<span class='editMember'><a href='#'>Edit</a></span>" .
"<br></div>";
}
And in your delete.php :
<?php
$id=(int) $_POST['myid'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id=".$id;
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
No need to add extra form element for Delete or Edit purpose. Try this way to pass the id of row for Eelete or Edit operation
while($row = $result->fetch_assoc())
{
$id=$row['id'];// capture your row id & pass to your delete & edit
echo
"<div class='trow'>" .
$row["id"]. ": " .
$row["firstname"] . " " .
$row["lastname"]. " " .
$row["joinDate"]. " " .
"<span class='deleteMember'>
<a href='deleteMember.php?id=<?=$id;?>'>Delete</a>
</span>" . " " .
"<span class='editMember'>
<a href='editMember.php?id=<?=$id;?>'>Edit</a>
</span>" .
"<br>
</div>";
}
EDIT:
Then catch the id on your relevant page for your operation.
//deleteMember.php
<?php
$id=$_GET['id'];
// sql to delete a record
$sql = "DELETE FROM customers WHERE id='".$id."'";
if ($conn->query($sql) === TRUE) {
header("Location: index.php");
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Note: Please Use Prepared Statements of PDO or MYSQLi instead to avoid SQL Injection and manual escaping.
Okay so my code works pretty well so far, it all goes through, my only problem is that when I try and print the unordered list and it's contents I get nothing. When I view my source code I have <ul> </ul>. There's a space, so surely something is happening.
This is my code, I have commented it slightly but what's happening is obvious:
$uname = mysqli_real_escape_string($link, $_SESSION['Username']); //Get username ready
$sql = mysqli_query($link, "SELECT * FROM users WHERE Username = '" . $uname . "'"); //SQL Query result
if(!$sql)
{
echo "Error retrieving User ID. Please try again. MySQL Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
$uid = $row['UserID']; //Obtain UserID
}
else
{
echo "Error: " . mysqli_error($link) . "<br />" . $uname . " / " . $sql . " / " . $uid;
}
mysqli_free_result($sql);
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
elseif($row = mysqli_fetch_assoc($sql))
{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
else
{
echo "Error: " . mysqli_error($link);
}
Where am I going wrong? The only thing it doesn't do is actually pick up any results and I've put some data into the table so there are entries! Otherwise it would say there aren't any. I've reversed this so it shows the message if there aren't 0 entries and that works. What am I doing wrong guys?
Thanks in advance.
You are fetching the result twice. Instead, only fetch the result in the while loop:
<?php
$sql = mysqli_query($link, "SELECT * FROM auditions"); //Get everything from the auditions table
if(!$sql)
{
echo "Error retrieving auditions. Please try again later. Error: " . mysqli_error($link);
}
else{
if(mysqli_num_rows($sql)==0)
{
echo "Sorry, there are currently no open auditions. Please try back at a later date.";
}
else
{
echo "<ul>";
while($row = mysqli_fetch_assoc($sql))
{
echo "<li><a href='auditions.php?id=" . $row['AudID'] . "'>" . $row['AudName'] . "</a></li>";
}
echo "</ul>";
}
}
?>
See this link for more information regarding mysql_fetch_assoc