I am currently learning PHP Programming,
I wanted to show error when the inputted data exists.
Can anyone show some example on how it doest work?
Here is code I used:
<?php
ob_start();
session_start();
require '../database/database.php';
// require '../database/inc_config2.php';
require ('p_nav.php');
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//Variable input data
//include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
// variables for input data
$pcat = $_POST['pcat'];
if($pcat=='')
{
//javascript use for input checking
echo"<script>alert('Please enter Category')</script>";
// echo 'Empty Category';
header ("location:..\product\p_cat.php");
exit();
}
// variables for input data
//check if category is exist
//here query check weather if user already registered so can't register again.
$check_pcat_query="select * from pcategory WHERE pcat='$pcat'";
// $check_user_query="select * from users WHERE user_name='$user_name'";
$run_query=mysqli_query($dbcon,$check_pcat_query);
if(mysqli_num_rows($run_query)>0)
{
//echo "<script>alert('Category $pcat is already exist in our database, Please try another one!')</script>";
exit();
}
// sql query for inserting data into database
//temporary disabled
$sql_query = "INSERT INTO pcategory(pcat) VALUES('$pcat')";
mysql_query($sql_query);
//echo "Supplier Added Successfully";
//header ("location:..\product\index.php");
exit();
/*
$insert_user="insert into pcategory (pcat) VALUE ('$pcat')";
if(mysqli_query($dbcon,$insert_user))
{
// echo"<script>window.open('welcome.php','_self')</script>";
echo "Welcome";
} */
}
// sql query for inserting data into database
?>
There is an error, you are using both MySQL and MySQLi, using both is fatal error if you work on live server. Just focus on MySQLi as MySQL is deprecated officially and is not supported anymore.
Now come to your question. Your logic seems to be fine a bit. This is how you have to implement:
Fetch values from FORM
First clean the input using mysqli_real_escape_string() function.
Use above values and check the record existance in the database (here use SELECT statement)
If mysqli_num_rows() gives you result greater than 0 than;
(a) it means record already exists
(b) else, execute INSERT statement
Related
so i have been playing with this website of mine for over a year and still have very little understanding of session management.
i had a login script somewhere but thats hidden from me, not an issue though il find it.
but obviously without a session manager of some kind login is worthless.
i had a little idea the other day and drew a pretty flowchart on ways i can setup security.
but mysqli is slowing me down.
I had the idea to store a username in a cookie, this value can be compared with the database to find the last used session ID then compare that with the phpsesid cookie and finally refresh the id to something new and replace that in the db, this would mean anyone with an outdated session token would have to log back in, blah blah, sorry il get to the point.
so while building the new session manager im having issues pulling data from mysql
if(isset($_COOKIE[$cookie_name])){
require_once ("bin/sql.php");
//plan to put another if statement here when the sql works
$sql = "SELECT '$_COOKIE[$cookie_name]' FROM DB.TBL;";
echo $sql . "<br>"; //debugging
$uiddb = new sqlflow;
$uiddb-> db_query($sql);
for debugging i have substituted the $sql to select a predefined username in the db, there will eventually be an 'if generic user, do other'.
the sql doc is abit of a mess, i have tried a few different variations after searching google, but common results are 'can not convert to string', unknown index, and even trying to pull as an array isnt working
mysqli_fetch
mysqli_store
misqli_use
all return 'expected 1 peram found 0'
and when i use the results var 'expected peram to be mysqli'
i have even taken the contents of the var and used it as the peram, thats when i seem to get the undefined index
function db_query($value){
$connect = self::db_connect();
$result = mysqli_query($connect,$value);
i have not been able to get anything after this to work.
what im trying to do is pull info from database such as the PID+SESID of the user, so i can query the other 2 tables for further information such as last known IP.
I'm not really sure what's your problem. But here some examples how to use mysql connection in php:
Database
For your DB-connection you can use a single file.
/* db-connect.php */
<?php
# Neue Verbindung: Diese Variable kann global aufgerufen werden
$verbindung = new mysqli('db-server-adress', 'database-user', 'userpassword', 'database');
if($verbindung->connect_error)
{
printf("Connect failed: %s\n", $verbindung->connect_error);
}
# Über diese Funktion können vereinfacht MySQL-Befehle abgesetzt werden
function query($sql)
{
global $verbindung;
if($result = $verbindung->query($sql))
{
return $result;
}
else
{
$verbindung->error;
}
}
?>
Now everywhere you need a connection to your database you can include this file:
/* Include the Database-Connection */
include 'db-connect.php';
With this you can call ths function "query" with every query you want to send to your mysql-db:
/* with the function query() you can call any sql-statement and box the result to a variable */
$queryresult = query("SELECT iduser FROM tbluser WHERE username='testuser';");
/* num_rows is the numbers of rows that were found by your query: */
if($queryresult->num_rows != 0)
{
/* Fetch each found row of the query */
while($fetchedQuery = $queryresult->fetch_assoc())
{
/* Call a single attribute from the current fetched row */
echo $fetchedQuery['iduser'];
}
}
else
{
echo 'no result';
}
Cookie
I suggest to you to first box the result of your cookiename. But remember it's a vulnerability to store privat information in cookies:
session_start();
$cookie_name = $_COOKIE[$cookie_name];
if(!empty($cookie_name))
{
$resultcookie = query("SELECT iduser FROM tbluser WHERE username='$cookie_name';");
if($resultcookie->num_rows != 0)
{
$fetchedcookie = $resultcookie->fetch_assoc();
/* Create a new session with the username in it */
$_SESSION['user'] = $fetchedcookie;
}
else
{
echo 'Cookie not found';
////// More Code /////
}
}
Session Put the function session_start() at the top of every document:
<?php
session_start();
/* Check if the Session user exists with this client */
if(isset($_SESSION['user']))
{
echo 'Session is set';
}
else
{
echo 'session is not set';
}
/////////// Destroy a Session ///////////
session_destroy();
I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!
Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.
I'm creating an e-commerce website. I am working on an admin page that lets the "store manager" log in to do things like add or remove products. In my database, I created a table called admin, with these fields:
id
password
time_last_logged_in
I inserted a row for my store manager, I can see the username and password so I know the person exists in the database, but when I try to log in it echoes out the error below.
admin_login.php
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
**echo 'That information is incorrect, try again Click Here';**
exit();
}
}
?>
I use a connect_test.php script to verify that it's connecting to the database and that there's no problem connecting.
index.php
<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: admin_login.php");
exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 0) { // evaluate the count
echo "Your login session data is not on record in the database.";
exit();
}
?>
Why might my code return That information is incorrect, try again Click Here'; instead of a successful validation?
The Problem(s?)
The way I see it, there are several problems with your code. I'll try to address each one and tell you how to solve each issue.
Issue #1: You are using REGEX To strip your code.
There are much better alternatives, the best of which is prepared statements which you should obviously use. Sadly, mysql_* functions don't support it. Which get's me to the next issue:
Issue #2: You are using mysql_* functions.
You shouldn't be using functions like mysql_query() and mysql_num_rows(), instead, consider moving to a better and more secure alternative, such as MySQLi (Good) or PDO (Awesome).
Issue #2.5: You are not using prepared statements.
A Prepared statement is automatically escaped and any malicious code or characters is render useless, same goes for SQL injections. You should use a better database handler that supports it (See Issue #2).
Issue #3: You are testing specifically.
You seem to test only if the row count is equal to exactly one. But what if there are (by accident) 2? Instead of testing what should be, test for what should not be:
if ($existCount != 0) { ...
Issue #4: You are not selecting the correct fields.
You only select the id field in your query, where instead you should be selecting all of the relevant fields (like username and password), in order to receive information.
Issue #5: You are not using secure storing.
If someone were to steal your database, they would have easy access to all your passwords. Consider using an encrypting method like sha1().
Issue #6: You are not testing for errors.
Errors can and will occur, you should test for them, with mysql_query() you should probably do something like
mysql_query("SELECT....") or die(mysql_error());
In PDO that would be something like
if (!$stmt->execute()) { throw new Exception("Execution failed.` . var_export($stmt->errorInfo(), true)); }
Try to correct those, and tell us if your problem persists.
Good luck :)
Try doing:
$sql = mysql_query("SELECT ... LIMIT 1") or die(mysql_error());
Your code assumes the query succeeds, which is very bad form. Always check for error conditions. You may have failed to connect to the database. perhaps your DB is malformed and you've got 2 or more records with the same username/password combo, etc...
I'm new to PHP myself, but I noticed that your select statement in the first code sample above selects only the id. That might be the problem. You should change it to select * and see if that makes any difference.
Good luck