PHP update table using MySQL - php

I have student table in my DB , and I need to create extra form in student page so he can update the details. However im getting this error ( Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\wamp\www\WebInterfaceLogIn\studentEdit.php on line 81)
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
include ('includes/connection.php');
// Create connection
if (isset($_POST["submit"]))
{ //Determine if a variable is set and is not NULL.
if (!empty($_POST['ID']) && !empty($_POST['user']) && !empty($_POST['surr']) && !empty($_POST['course']) && !empty($_POST['mail']) && !empty($_POST['pass']))
{ //Determine if user enters both user name and password.
$ID = $_POST['ID']; // enters user ID in database
$user = $_POST['user']; // enters user name in database
$surr = $_POST['surr']; // enters user surname in database
$course = $_POST['course']; // enters user course in database
$pass = $_POST['pass']; // enters password in database
$mail = $_POST['mail'];
// $query = mysqli_query($con,"SELECT * FROM students WHERE Student_ID='".$ID."'"); // change to update
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");
$numrows = mysqli_num_rows($query);
if ($numrows == 0)
{
$sql = "INSERT INTO students(Student_ID,Name,Surname,Course,email,password) VALUES('$ID', '$user','$surr','$course','$mail','$pass')"; // insert user name and password to database
$result = mysqli_query($con, $sql);
// Checks does user enters the details
if ($result)
{
echo '<script language="javascript">;
alert("Account Successfully Updated");
document.location.href="index.php";
</script>';
}
else
{
echo mysqli_error($con);
}
}
}
else
{
echo '<script language="javascript">
alert("All fields required")
</script>';
}
}
Can anyone can help to solve this problem?

You need pass connection object to function mysqli_query, something like this:
mysqli_query($con,"UPDATE students SET `course` = " .$_POST['course']. ", `email` = " .$_POST['mail']. " Student_ID='".$ID."'");
See more details on:
http://www.w3schools.com/php/func_mysqli_query.asp

The error is explicit enough.
add $con as a first parameter to your mysqli_query function on this line:
$query = mysqli_query("UPDATE students SET `course` = " . $_POST['course'] . ", `email` = " . $_POST['mail'] . " Student_ID='" . $ID . "'");

Related

Editing user profile: How to avoid user from entering duplicate values?

I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.

PHP Update Confusion

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");
}

Validation for username not working

I have written this code , its working to add users but for duplicate user it again saved the value os same user name. i wanted to give popup message if username already taken. i m beginner please help.
<?php
ob_start();
include("db.php");
if(isset($_POST['send'])!="") {
$username = mysqli_real_escape_string($con, $_POST['username']);
$usermail = mysqli_real_escape_string($con, $_POST['usermail']);
$usermobile = mysqli_real_escape_string($con, $_POST['usermobile']);
$bool = true;
$con = mysqli_connect("localhost","root","","demo");
$result = mysqli_query("SELECT `username` FROM `sample` WHERE username = '$username'");
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
}
if ($bool) {
$inssql = "insert into sample set
username = '" . $username . "',
emailid = '" . $usermail . "',
mobileno = '" . $usermobile . "',
created = now()";
$update = mysqli_query($con, $inssql);
}
}
Make sure you finish the script or turn off your flag before making the insert:
if(mysqli_num_rows($result)>0)
{
Print '<script>alert("Username has been taken!");</script>';
die('username already taken');
//$bool = FALSE;
}
If you still having duplicate entries, debug what is the result of $username and compare it with the value in the database.

Php - Two-Way Login Form [Admin & User]

I am trying to make a login form which is able to detect whether the user is admin or non-admin. I tried the following but when i run it i get no results:
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$r = mysqli_fetch_array($a);
if(is_array($row))
{
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
}
elseif(is_array($r))
{
$_SESSION["admin"] = $row[id];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
?>
When i insert the username and password for admin it reloads the login form.
UPDATE 1:
The non-admin part is just working fine but the admin part redirects/reloads itself to the login form.
you should check your login post form,should have a code like this:
<form name="loginform" method="post" action="check.php">
if your 'action' vlaue is invalid,the page may refresh.
you should confirm that your login form is posted to the php page you posted.
Try this, lets see what happens.
session_start();
$msg = "";
if(count($_POST)>0){
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$stdCount = mysqli_num_rows($result);//counts the number or rows returned from student table
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$tchrCount = mysqli_num_rows($a);// same but with teachers table
if($stdCount != 0){
$row = mysql_fetch_array($result);
$_SESSION['id'] = $row['id']; //set session for non admin.
}else if($tchrCount != 0){
$r = mysql_fetch_array($a);
$_SESSION['admin'] = $r['id'];
}else{
echo "Username and Password is not Matching.";
}
}//end of the main if
I have not tested this code so dunno if it works or not but I think you got the logic.
use quotes: $row["id"]
"Location: " must be capital.
after calling the "header" function make sure you use "exit".
This code is not tested, but if I understood correctly, should work.
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_student = mysqli_fetch_array($result_student);
$result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_teacher = mysqli_fetch_array($result_teacher);
if(is_array($result_student))
{
$_SESSION["id"] = $row_student["id"];
$_SESSION["name"] = $row_student["name"];
$_SESSION["admin"] = 0;
}
elseif(is_array($result_teacher))
{
$_SESSION["id"] = $row_teacher["id"];
$_SESSION["name"] = $row_teacher["name"];
$_SESSION["admin"] = $row_teacher["id"];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
if(#$_SESSION["admin"]>0)
{ header ("Location: gui-admin.php");
exit;
}
else
{ header("Location: user_dashboard.php");
exit;
}
}
?>
Hope it helps....
But I can guess why you are facing the problem for your code only working for students.
In this -
if(is_array($row))
is_array($row) would always be returning true and the code goes on to execute
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
but $row[id] would be empty because there are no rows matching the criteria, so $_SESSION["id"] would not be assigned and when this is executed -
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
None of the if statements would not be executed because none of them are set. This is my analysis. This could be wrong.
Try the solution below -
You should combine the users table for just querying whether the user is a student or a teacher. You then query the student table or the teacher table depending on the Main "Users" table. Querying for the same username and password to two tables doesnt look good.
You can change the meta tag in my code to header("Location: $url") but I would prefer this so that the request doesnt get cached by the user.
Hope it helps :-
$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection.
$result=mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result))
{
$fetch=mysqli_fetch_row($result);
$_SESSION["id"]=$fetch['userid'];//Just fetching all details
$_SESSION["Name"]=$fetch['name'];//and making session variables for that.
$_SESSION["username"]=$fetch['username'];
$isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.
if($isadmin) //checking whether admin or not
{
$_SESSION["isadmin"]=1;
echo "<meta http-equiv='refresh' content='0;url=adminurl'>"; } //if admin redirect to different url
else{
$_SESSION["isadmin"]=0;
echo "<meta http-equiv='refresh' content='0;url=userurl'>";
}
}
else
{
//Username Password Incorrect
/* Show FORM HERE */
}
First of all, you have to know that's really a bad idea to use your POST data directly in your SQL request, you have to avoid that and to clean your data using a function like mysqli_real_escape_string. Also, you have to secure your passwords and avoid to save it clear into your DB, for that take a look on the best way to store password in database.
For your two SQL requests, you can use mysqli_multi_query like I did in this example where I used the same script to get POST data and show the login form :
<?php
if(count($_POST) > 0){
session_start();
$link = mysqli_connect('localhost', 'user', 'pass', 'db');
if(mysqli_connect_errno()) {
die('db connection error : ' . mysqli_connect_error());
}
function secure_password($password){
// secure your password here
return $password;
}
// escape special characters
$user_name = mysqli_real_escape_string($link, $_POST['user_name']);
// you have to secure your passwords, when saving it of course
$password = secure_password(mysqli_real_escape_string($link, $_POST['password']));
$query = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
$query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";
$is_teacher = FALSE;
if(count($_SESSION)) session_destroy();
// you can use mysqli_multi_query for your two requests
if (mysqli_multi_query($link, $query)) {
do {
if ($result = mysqli_store_result($link)) {
if ($row = mysqli_fetch_row($result)) {
if($is_teacher){
$_SESSION['admin'] = $row[0];
} else {
$_SESSION['id'] = $row[0];
$_SESSION['name'] = $user_name;
}
}
mysqli_free_result($result);
}
if (mysqli_more_results($link)) {
// if we have more results, so it's a teacher record
$is_teacher = TRUE;
}
} while (mysqli_more_results($link) && mysqli_next_result($link));
}
mysqli_close($link);
if(isset($_SESSION['id']))
{
header('Location:user_dashboard.php');
}
elseif(isset($_SESSION['admin']))
{
header('Location:gui-admin.php');
}
// no redirection, show the message and the login form
echo 'Invalid Username or Password!';
}
?>
<form action='p.php' method='post'>
User name : <input type='text' name='user_name'><br>
Password : <input type='password' name='password'><br>
<input type='submit' value='Submit'>
</form>
Hope that can help.

Two queries using Mysqli

Problem:
Trying to run two MySQLi queries against the database but results always into a failure message.
Code (PHP):
// Checks whether submit button has been pressed
if (isset($_POST['submit']))
{
// Gets values from form fields
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
// Selects e-mail in database
$query = "SELECT * FROM userlogin WHERE email = '{$email}'";
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Checks whether e-mail exist
if (mysqli_num_rows($result) != 0)
{
// Register new user
$query = "INSERT INTO
userlogin
(username, password, email, regdate)
VALUES
('James','{$password}', '{$email}', NOW())
";
// Submit query to database
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Return success message
header('Location: index.php?notification=success');
}
else
{
// Return failure message
header('Location: index.php?notification=fail');
}
}
What am I missing? Any advice is appreciated.
Shouldn't this
mysqli_num_rows($result) != 0
be
mysqli_num_rows($result) == 0
One issue is
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
and should be
$email = mysqli_real_escape_string($link,stripslashes($_POST['email']));
$password = mysqli_real_escape_string($link,stripslashes($_POST['password']));

Categories