I have a form where i save students login data to a database. The form includes the "admission_number", "username" and "password" fields. i want to show an error if the admission number is already existing and a user tries to add it again. Here's my php code for inserting the record.
<?php
if(isset($_POST['submit']))
{
$server = 'localhost';
$username = 'root';
$password = '';
$course_code=$_POST['course_code'];
$course_title=$_POST['course_title'];
$course_units=$_POST['course_units'];
$course_semester=$_POST['course_semester'];
$con=($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $password));
if(!$con)
{
exit('Error: could not establish connection to the server');
}
else
{
$con_db=((bool)mysqli_query($con, "USE esther"));
if(!$con_db)
{
exit('Error: Failed to connect to the database');
}
else
{
if(!empty($course_code) && !empty($course_title) && !empty($course_units) && !empty($course_semester))
{
$insert="INSERT INTO `course_table` VALUES('', '".$course_code."' ,'".$course_title."','".$course_units."','".$course_semester."')";
$query=mysqli_query($GLOBALS["___mysqli_ston"], $insert);
$dup_admission_number = mysql_query("SELECT admission_number FROM users_table WHERE admission_number = $admission_number");
}
if (#mysql_query($dup_admission_number)) {
echo 'Your admission number is already in our database.';
exit;
}
if($query)
{
echo 'course added successfully!';
header("location:add_course.php");
}
else { echo 'Error while adding Course.'; }
}
else
{
echo '*** fields cannot be blank ***.';
}
}
}
?>
To check admission number is unique or not you have to execute bellow query
$sql: "select id from student where admission_number = <> LIMIT 0,1";
if this query show result then you current form's admission number is not unique.
this process you can do using ajax request or you can check it before insert query being process.
or you can manage it in mysql by giving unique key constraint to admission number.
This is the Mysql Query
INSERT INTO sometable (data1, data2, data13)
SELECT 'username' FROM sometable
WHERE NOT EXISTS
(SELECT username FROM sometable WHERE login='someusername');
Related
How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.
I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify
i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .
Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
This code really made me confused.
The first and second time I ran it, it worked perfectly but after that it stopped working
Let me explain it:
I work with 2 tables.
The first table I insert to it the current date, current time and the id of the user the id I take it from the session.
Which I believe works fine.
My problem is in the second table the error I get is the error i typed in the " print " after the second insert.
this is my code :
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if (!$con) {
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if (!$db) {
die("unable to select database");
}
//first table
$qry="insert into shipment values('',NOW(),CURTIME(),'".$_SESSION['con_id']."');";
$resultop=mysql_query($qry);
//to take the id frome last insert because i need it in the second insert
$SNo=mysql_insert_id();
if ($resultop) {
$options=$_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");}
// this is the second table .. my reaaal problem
$qun=$_POST['Quantit'];
$size =count($options);
for ($i =0; $i<$size; $i++) {
$qqry="insert into shipmentquantity values('".$options[$i]."','".$SNo."','".$qun[$i]."');"; // $options is array of the id's which i took from the checkbox's in the html ... $qun is array of the values i took form html ... i sure this is right ;)
$resultqun=mysql_query($qqry);
}
if ($resultqun) {
header("location: shipment_order.php");
}
else print "error in the Quantity";
}
else print "error in the shipmet";
Just add some debug statements to find out what is going wrong. Something like -
$resultqun = mysql_query($qqry) or print mysql_error();
You need to do some reading about SQL injection as this script is vulnerable. Checkout these pages on the use of prepared statements - PDO::prepare and mysqli::prepare
UPDATE - here is an example using PDO to interact with your db -
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$db = new PDO("mysql:dbname=$DB_DATABASE;host=127.0.0.1", $DB_USER, $DB_PASSWORD);
//first table
$qry = "INSERT INTO shipment VALUES(NULL, CURRENT_DATE, CURRENT_TIME, ?)";
$stmt = $db->prepare($qry);
$resultop = $stmt->execute(array($_SESSION['con_id']));
if(!$resultop){
print $stmt->errorInfo();
} else {
$SNo = $db->lastInsertId();
$options = $_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");
exit;
}
// this is the second table .. my reaaal problem
$qun = $_POST['Quantit'];
$size = count($options);
$stmt = $db->prepare("INSERT INTO shipmentquantity VALUES(?, ?, ?)");
for($i = 0; $i < $size; $i++) {
$resultqun = $stmt->execute(array($options[$i], $SNo, $qun[$i]));
}
if($resultqun) {
header("location: shipment_order.php");
} else {
print $stmt->errorInfo();
}
}
What is your primary key for the 'shipmentquantity' table? It looks like you are trying to enter two values of '3' for the primary key and that's where it's going awry.
DESCRIBE `shipmentquanitity`