i need your help. I have my delete all records button, when i delete all records it works fine until when i try to add records after the delete all, the first record will be deleted when i try to add the second record. i think the problem is because i never close my query after the delete all records.. i dont the exact syntax that can be used in my codes. please help me guys.
here is my code for delete all:
<?php
include_once 'connection.php';
$fname = $lname = $username = $phone = $email = $cemail = "";
$act="";
$txtid = 0;
if(isset($_GET['act'])){
$act=$_GET['act'];
if($act=='delete'){
$id=$_GET['id'];
$sql="delete from tbl_admin where id = $id";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
if($result){
}
}
if($act=='deleteall'){
$sql="delete from tbl_admin";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
}
if($act=='edit'){
$id=$_GET['id'];
$sql="select * from tbl_admin where id = $id";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
while($row = mysqli_fetch_array($result)){
$txtid = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$username = $row['username'];
$phone = $row['mobileNo'];
$email = $row['email'];
}
}
if(isset($_POST['add'])){
// fname validate
if(empty($_POST["fname"])){
echo '<script> alert("first name is empty!"); </script>';
}else{
$fname = test_input($_POST["fname"]);
// lname validate
if(empty($_POST["lname"])){
echo '<script> alert("last name is empty!"); </script>';
}else{
$lname = test_input($_POST["lname"]);
//username
if(empty($_POST["username"])){
echo '<script> alert("username is empty!"); </script>';
}else{
$username = test_input($_POST["username"]);
//phone
if(empty($_POST["phone"])){
echo '<script> alert("mobile number is empty!!"); </script>';
}else{
$phone = test_input($_POST["phone"]);
//email
if(empty($_POST["email"])){
echo '<script> alert("email is empty!"); </script>';
}else{
$email = test_input($_POST["email"]);
//cemail
if(empty($_POST["cemail"])){
echo '<script> alert("confirm email is empty!"); </script>';
}else{
$cemail = test_input($_POST["cemail"]);
if($email != $cemail){
echo '<script> alert("Confirm Email!"); </script>';
}else{
$sql= "insert into tbl_admin(fname,lname,username,password,mobileNo,email,add_date) values('$fname','$lname','$username','123abc','$phone','$email',NOW())";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
if($result){
echo '<script> alert("Successfully add admin user."); </script>';
$fname = $lname = $username = $phone = $email = $cemail = "";
}
}
}
}
}
}
}
}
}
if(isset($_POST['update'])){
if(empty($txtid)){
echo '<script>
alert("Select record to Update!");
</script>';
}else{
echo '<script>
alert("you can update record..");
</script>';
$fname = $lname = $username = $phone = $email = $cemail = "";
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Because ALL your code exists inside this if statement
if(isset($_GET['act'])){
Then we have to assume that $_GET['act'] is always set to something
Because $_GET['act'] is always set to something then the DELETE code is getting run ALWAYS. Either its delete or deleteall
The code that rebuilds your web page is still missing, but basically you need to organise your code more logically, and also make sure that $_GET['act'] is only set when you actually want to do a delete, which would probably mean changing the HTML so it is not being left set.
I guess the methods are the same as it was in mysql (without i)
http://php.net/manual/en/mysqli-result.free.php
with non-object-oriented way it would be
mysqli_free_result($result);
Related
How do I echo message at the top of the form, after performing insertion, update and delete on same page, while using header("location:$url");
if($_SERVER["REQUEST_METHOD"] == "GET"){
if(isset($_GET['id1'])){
$Id1 = base64_decode($_GET['id1']);
$qry = "SELECT Name,Description,Role FROM cms WHERE id='$Id1'";
$res = mysqli_query($conn, $qry);
$res1 = mysqli_fetch_assoc($res);
$uname = $res1['Name'];
$address = $res1['Description'];
$role1 = $res1['Role'];
}
}
if(isset($_POST['update']))
{
if(isset($_GET['id1']))
{
$id1=base64_decode($_GET['id1']);
$uname = $_POST['uname'];
$address = $_POST['address'];
$role = $_POST['role'];
$qry2 = "UPDATE cms SET Name ='$uname', Description = '$address',Role='$role' WHERE
id='$id1'";
$res2 = mysqli_query($conn,$qry2);
if(mysqli_error($conn))
{
echo "error";
} else {
$_SESSION['success'] = "Record Updated Successfully!";
header("location:admin.php");
}
}
}
?>
I tried running the above code in HTML snippet to display the echo message on my webpage but it does not echo the message with header tag
I am updating MySQL row using the following code. could any one tell me how i can error check the update query and only print Success if the update query was successful without any error? and print failed if update query was not successful!
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
// $get_contact = "SELECT * FROM `contacts` where contacts_id = '$contact_id'";
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '$contact_id'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='$fname',`last_name`='$lname',`cellphone_number`='$cphone',`city`='$city' WHERE contacts_id = ". $contact_id;
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
My question is this: I'm doing my best to find whats the error and i couldn't what it is. It is for my elective project.
first of all please learn how to use procedure based query to be safe from SQL injection( I am not here to give tutorials on procedure and SQL injection, it is just warning against malicious code) and now your code solution. There was a problem in the way you were concatenating a variable with a string in your query. I have fixed that part for you.
if you still get any error then share what error you are getting and what is the error message.
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '".$contact_id."'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='".$fname."',`last_name`='".$lname."',`cellphone_number`='".$cphone."',`city`='".$city."' WHERE contacts_id = '".$contact_id."'";
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
use this function:
function alertBox($alert_msg, $redirect_link)
{
$alert = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$alert .= '<script type="text/javascript">alert("'.$alert_msg.'");';
if(!empty($redirect_link)):
$alert .='window.location="'.$redirect_link.'";';
endif;
$alert .='</script>;';
return $alert;
}
// and for calling..
if((mysqli_query($con,$sql))
{
echo alertBox("sucessfull","example.php");
}
<?php
$con = mysqli_connect("localhost","root","","social_network") or die("Connection was not established");
function InsertUser(){
global $con;
//if sign up button is pressed
if(isset($_POST['sign_up'])){
$name = $_POST['u_name'];
$pass = $_POST['u_pass'];
$email = $_POST['u_email'];
$country = $_POST['u_country'];
$gender = $_POST['u_gender'];
$b_day = $_POST['u_birthday'];
$name = $_POST['u_name'];
$date = date("d-m-y");
$status = "unverified";
$posts = "No";
//checks if the email already existist in the system
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con,$get_email);
$check = mysqli_num_rows($run_email);
//if email validation
if ($check==1) {
echo "<script>alert('This email is already registered!, Try another one')</script>";
exit();
}
//password properties string length
if(strlen($pass)<8){
echo "<script>alert('Password should be minimum 8 characters')</script>";
exit();
}
else {
//inserting user input into the database
$insert = "INSERT INTO users (user_name,user_pass,user_email,user_country,user_gender,user_dob,user_image,register_date,last login,status,posts) VALUES ('$name','$pass','$email','$country','$gender','$b_day','default.jpg','$date','$date','$status','$posts')";
$run_insert = mysqli_query($con,$insert);
if($run_insert){
echo "<script>alert('Registration Successfull!')</script>";
}
}
}
}
?>
The mistake is in your query
cant give a column name like "last login"
Remove the space between and try to change the column name of "status" to anything else
I've checked dozens of threads on here and on other sites, and I cannot figure out why my code is not working. I am trying to use PHP to update MySQL using a variable to identify WHERE. The code I have works if I swap the variable for a number, and the variable works everywhere else in my script. It's just this one line that does not.
The line in question is:
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";
I've also tried the following:
$change = mysqli_query("UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'");
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id=".$id;
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
From what I've seen on other threads, at least one of these should worked for me.
Can anyone point me in the right direction, please?
If it helps the entire string of PHP code is:
<?php
$fnameErr = $lnameErr = $emailErr = $experienceErr = $regEventErr = "";
$fname = $lname = $email = $experience = $regEvent = "";
$id = $_GET["id"];
$errors = "yes";
$servername = "localhost";
$username = "root";
$password = "5tTtFzaz6dIO";
$database = "project2db";
$conn = new mysqli($servername, $username, $password, $database);
$query = mysqli_query($conn, "SELECT * FROM reg_info where id=".$id);
$row = mysqli_fetch_array($query, MYSQLI_NUM);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First name is required";
$errors = "yes";
} else {
$fname = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Last name is required";
$errors = "yes";
} else {
$lname = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$errors = "yes";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["experience"])) {
$experienceErr = "Experience level is required";
$errors = "yes";
} else {
$experience = test_input($_POST["experience"]);
$errors = "no";
}
if (empty($_POST["additional"])) {
$regEvent = "";
} else {
$additional = test_input($_POST["additional"]);
}
if (empty($_POST["regEvent"])) {
$regEventErr = "Event is required";
$errors = "yes";
} else {
$regEvent = test_input($_POST["regEvent"]);
$errors = "no";
}
if($errors == "no") {
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
$result=$conn->query($change);
if ($result) {
echo '<script language="javascript">';
echo 'alert("New record created successfully.")';
echo '</script>';
header('Location: regtable.php');
} else {
echo '<script language="javascript">';
echo 'alert("Error. New record not created.")';
echo '</script>';
header('Location: regtable.php');
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I figured out the issue! Whenever the form was submitted, the new POST data did not have anything assigned to the html id="id" that was passed into the PHP code to create the $id variable.
Since there was nothing in the form, $id was null, and thus the query did not update the database, even though the query and connection were completely valid.
Thanks to everyone who posted comments and advice, I really appreciate it.
Since the query in itself is valid, I can only guess that somehow the data is causing the issue. Try the following, which escapes every value that will be used in the query:
$fname = mysqli_real_escape_string( $conn, $fname );
$lname = mysqli_real_escape_string( $conn, $lname );
$email = mysqli_real_escape_string( $conn, $email );
$experience = mysqli_real_escape_string( $conn, $experience );
$additional = mysqli_real_escape_string( $conn, $additional );
$regEvent = mysqli_real_escape_string( $conn, $regEvent );
$id = mysqli_real_escape_string( $conn, $id );
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";
For an unregistered email, I want the user to be prompted with "Login Failed : Email Not Registered." and for a wrong password, "Login Failed : Please Enter The Right Email/Password Combination.".
However, I tend to see "Login Failed : Please Enter The Right Email/Password Combination." for both errors.
Here's my code :
<?php
if(isset($_POST['Login'])){
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$result = $con->query("select * from user where Email='$Email'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($PW, $row['Password'])){
session_start();
$_SESSION["UserID"] = $row['UserID'];
$_SESSION["FName"] = $row['Fname'];
$_SESSION["LName"] = $row['Lname'];
$_SESSION["City"] = $row['City'];
$_SESSION["Country"] = $row['Country'];
$_SESSION["Timer"] = $row['Timestamp'];
header('Location: Account.php');
}
elseif($result === false)
{
$msg = "Login Failed : Email Not Registered.";
}
else
{
$msg = "Login Failed : Please Enter The Right Email/Password Combination.";
}
}
?>
<div class="form-group">
<?php
if(isset($msg) & !empty($msg)){
echo "<span style='color: red;'>$msg</span>";
}
?>
Try this:
$result = $con->query("select * from user where Email='$Email'");
if($result->num_rows>0){
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($PW,$row["password"])){
//blah blah blah
}
else
{
$msg = "Login Failed : Please Enter The Right Email/Password Combination.";
}
}
else
{
$msg="Login Failed : Email Not Registered.";
}
Try this:
<?php
session_start();
if (isset($_POST['Login'])) {
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$result = $con->query("select * from user where Email='$Email'");
$row = $result->fetch_array(MYSQLI_BOTH);
if (!empty($row)) { // User found
if (password_verify($PW, $row['Password'])) { // Password correct
$_SESSION["UserID"] = $row['UserID'];
$_SESSION["FName"] = $row['Fname'];
$_SESSION["LName"] = $row['Lname'];
$_SESSION["City"] = $row['City'];
$_SESSION["Country"] = $row['Country'];
$_SESSION["Timer"] = $row['Timestamp'];
} else { // Password not correct
$msg = "Login Failed : Please Enter The Right Email/Password Combination.";
}
} else { // User not found
$msg = "Login Failed : Email Not Registered.";
}
}
<div class="form-group">
<?php
if(isset($msg) & !empty($msg)){
echo "<span style='color: red;'>$msg</span>";
}
?>
You are trying to use $result which will always returns False or TRUE. Check this manual. http://php.net/manual/en/mysqli.query.php
Here is the code. Hope it will work for you.
<?php
if(isset($_POST['Login'])){
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$result = $con->query("select * from user where Email='$Email'"); //// this will always returns false or ture on faliure or success which is not your need
$result_rows =$result->num_rows; // this will tell you if there in your database e-mail exits or not
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($PW, $row['Password'])){
session_start();
$_SESSION["UserID"] = $row['UserID'];
$_SESSION["FName"] = $row['Fname'];
$_SESSION["LName"] = $row['Lname'];
$_SESSION["City"] = $row['City'];
$_SESSION["Country"] = $row['Country'];
$_SESSION["Timer"] = $row['Timestamp'];
header('Location: Account.php');
}
elseif($result_rows === 0) //// no e-mail found !
{
$msg = "Login Failed : Email Not Registered.";
}
else //// email found and other operation what you want you can also use ///// elseif($result_rows > 0) ////
{
$msg = "Login Failed : Please Enter The Right Email/Password Combination.";
}
} ?>
Use empty($row) instead of $result == false in condition.
if(isset($_POST['Login']))
{
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$result = $con->query("select * from user where Email='$Email'");
$row = $result->fetch_array(MYSQLI_BOTH);
if(password_verify($PW, $row['Password']))
{
session_start();
$_SESSION["UserID"] = $row['UserID'];
$_SESSION["FName"] = $row['Fname'];
$_SESSION["LName"] = $row['Lname'];
$_SESSION["City"] = $row['City'];
$_SESSION["Country"] = $row['Country'];
$_SESSION["Timer"] = $row['Timestamp'];
header('Location: Account.php');
}
elseif(empty($row))
{
$msg = "Login Failed : Email Not Registered.";
}
else
{
$msg = "Login Failed : Please Enter The Right Email/Password Combination.";
}
}
elseif(empty($row))
{
$msg = "Login Failed : Email Not Registered.";
}
}