I made a small database(1 table) in phpMyAdmin. One of the fields I want to check is "Name".
I want to verify through PHP if a name that user types in a form exists in the database. In the html a list of names from DB appears, but the user might type wrong the name in the form.
The problem is the answer whether it exists or not varies.
I have 2 PHP files:
Connection.php and welcome.php
Connection
<html>
<head>
<title>Project</title>
</head>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM person");
$dbname="name";
#$formula_adr="formula_adr";
#$adress="adr";
$line=mysql_fetch_assoc($sql);
echo'Choose a name to whom you send e-card:<br/><br/>';
echo $line[$dbname].'<br/>';
while($line=mysql_fetch_assoc($sql))
echo $line[$dbname].'<br/>';
?>
<form action="welcome.php" method="POST">
Nume: <input type="text" name="fname" />
<input type="submit" value="Verify existance in DB"/>
</form>
</body>
</html>
And welcome:
<?php
mysql_connect("localhost","root","");
mysql_select_db("e-card");
$sql=mysql_query("SELECT * FROM persoana");
$dbname="name";
$formula_adr="formula_adr";
$adresa="adr";
$linie=mysql_fetch_assoc($sql);
if ($_SERVER['REQUEST_METHOD']=='POST' and isset($_POST['fname']))
{
$name = $_POST['fname'];
while($line=mysql_fetch_assoc($sql))
{
if(strcmp($name,$line[$dbname]))
{
echo 'Found';
}
else
{
echo 'This name doesn't exist in DB';
}
}
}
?>
THANK YOU IN ADVANCE ^_-
<?php
mysql_connect(HOST, USERNAME, PASSWORD);
mysql_select_db(DB_NAME);
if($_POST) {
$name = $_POST['fname'];
// check if name exists in db
$sql = "SELECT name FROM person WHERE name=' . mysql_real_escape_string($name) . '";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) {
// user exists
} else {
// user does not exist
}
}
The above script will work and will also protect your script against SQL injection by using the built-in mysql_real_escape_string method. I would also recommend against using a wildcard (*) selector when verifying data in this manner as it's a waste of resources to query any additional information that is unused.
Don't get all data from the table to compare for a name.
Do it this way:
$sql=mysql_query("SELECT * FROM persoana where name like '$name%'");
You will get result only if you have a match
I would follow these steps high level steps.
1 - use javascript to initially check on client side that something was entered BEFORE calling the DB. You can use a filter in your javascript to check that form field.
2 - If you verify that something *useful was entered - pass the form field value to another page or object that will parse the value and then query the table.
3 - Use the parsed value against the db table column that contains your data. If records are found, return them.
Use a SQL injection technique to prevent malicious intend by users who may type something evil into your form field.
Related
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
I would like to know how to make a text box for the user to type and then create a database named after this input.
<?php
/*
code to connect and make a mysql database named after the user input
*/
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action=<?php $_SERVER['PHP_SELF']; ?>>
<input type="text" name="databasename">
<input type="submit" name="submit">
</form>
</body>
</html>
It technically depends on the DBMS you use, but just make a SQL query (using MySQL) of "CREATE DATABASE databasename" would do it.
However, unless you're creating a database management tool like PhpMyAdmin, don't do this. You're just asking for users to run amok in your system.
And that's just the basics. I implore you to read the documentation on MySQL
You absolutely have to make sure the user's input is useable and not a hacking attempt or a mistake. So, first you check the input, and then if it's okay, you create a database.
This is assuming you add action="post" in the form. I don't like putting inputs into "get" because then your variable's part of the URL, and some people might try to set bookmarks with it there.
if(isset($_POST['databasename'])) { //this lets us know the form has posted
// 1. Check for acceptable name
$name = $_POST['databasename'];
$name = strtolower($name); //all lowercase (makes things easier to deal with)
$name = preg_replace("/[^a-z]/", '', $name); //get rid of things that aren't letters
if($name != '') {
// 2. Create the database
$mysqli = new mysqli('localhost', 'my_user', 'my_password');
if ($mysqli->connect_error) {
throw new Exception("Connect Error ($mysqli->connect_errno) $mysqli->connect_error");
}
$query = "CREATE DATABASE `$name`";
$mysqli->query($query);
if($mysqli->errno) {
throw new Exception("Error creating database: $mysqli->error");
// I am pretty sure this is enough to catch the error of the database already existing
}
echo "Database $name created.";
} else {
throw new Exception("Invalid name");
}
}
If I were you, I would put this in a try-catch to catch the exceptions and handle them.
As you haven't declared a method for your form it defaults to GET.
$db_name = $_GET['databasename'];
$host="localhost";
$user="username";
$password="pa55word";
$con=mysqli_connect($host,$user,$password);
// Create database
$query="CREATE DATABASE `$db_name`";
if (mysqli_query($con,$query))
{
echo "Database created";
}
else
{
echo "Error creating database...";
}
If the user isn't root though, you need to make sure you have granted the user enough privileges to create a database.
You can use this method to check if there exists a database with same name and through an error else create it and display created successfuly
<?php
if(isset($_POST['submit'])){ //check for the submit button pressed
$dbname=$_POST['db']; //store the database name in php variable
$query= mysqli_connect('localhost','root','')or die("Error establishing connection"); //check for database connectivity
$a="CREATE DATABASE IF NOT EXISTS ".$dbname; //create a database if it doesn't already exist
$q= mysqli_query($query, $a) or die("Database already exist.. please try different name");
echo "Your database ".$dbname." is successfully created";
}
?>
for the html form refer the code below:-
<form method="post" action="">
Enter database name: <input type="text" name="db" /><br/>
<input type="submit" name="submit" value="submit"/>
</form>
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.
New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?
I am developing my first simple website using PHP. Now, I am working in the admin page and I want to let him adding, deleting users and editing the personal information of the existed users. I did the adding and deleting. Now, I want to develop editing users. First of all, I want him to choose the user from drop list, then fetch the user information automatically after choosing him from the drop list, and after that editing his information. So how can I do that?
My code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="13524"; // Mysql password
$db_name="sharingi_db"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function reload(form){
var val=form.username.options[form.username.options.selectedIndex].value;
self.location='editUser2.php?username=' + val ;
}
</script>
</head>
<body>
<div id="content_main" class="admin_student_height">
<!-- Here starts the first form -->
<form method="get">
<h3>Choose A User</h3> <br />
select name="username" onchange="reload(this.form)">
<option>
<?php
if(isset($_GET['username']))
echo "{$_GET['username']}";
else echo "Select one";
?>
</option>
<?php
if(isset($_GET['username'])){
$exceptcc = $_GET['username'];
$sql = "SELECT username FROM user WHERE user.username NOT IN
('$exceptcc')";
}
else
$sql = "SELECT username FROM user";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "<option value={$row['username']}>{$row['username']}</option>";
}
?>
</select><br /><br />
<h3>User Information</h3> <br />
<?php
$thecc = $_GET['username'];
$sql = "SELECT Firstname FROM user WHERE Username=$thecc";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "{$row['Firstname']}>{$row['Firstname']}}";
}
?>
<br /><br />
</form> <br />
</div>
</div>
</body>
I've been working on making a web-based ticketing system and ran into this same situation.
I solved the problem like this:
When the page is loaded, determine if they have admin rights or throw them off the page.
Do an SQL Query to get the List of users, to either display in a list or in a drop down box.
Once the User to edit has been selected, Do another Query and load each item into a field;
what I did was use the same form for adding new users but have php build the form and insert the current values for that user into the fields.
When this form is submitted, (and submitter verifed) I have the php script look at the submitted username and use that for the where clause in the sql update statement
If you want me to post up an example of what I did I can do that.
You are only echo'ing the user's information.
Instead, you need to put the information into a form, which will allow for editing.
<?php
if ($_POST['submit']) {
$username = $_POST['username'];
//if you want to update
mysql_query("UPDATE users SET username = '$username', password = '$password'");
//if you want to delete
mysql_query("DELETE FROM users WHERE username = '$username'");
}
?>
<?
//show all users
$user_query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($user_query)) {
echo $row['username'] . ' ' . $row['first_name'] . ' ' . $row['last_name'];
//and so on.. depending on your table fields
}
?>
<form method="POST">
Username: <input name="name" value="<?echo $row['username'?>"/>
<input type="submit" name="submit"/>
</form>
Load data into your form, and add action to it like "save_user.php
On that page save_user.php get data from $_POST, $_POST["firstName"] where firstName is name of your text field where you have loaded data from db
write query "update tbl_users set FirstName='$firstName', Email='$email" and execute this query, because you are starter this can be enough but remember query written like this can be used for SQL Injection that means you can write SQL query into text field "firstname" and do some stuff, like delete all data or gain passwords, emails etc.
When you get this then use parameters in your MySQL query in order to avoid SQL Injection. But you will manage it.
if you want to fetch the user information automatically from the drop list (without clicking submit button), you need to use AJAX. Here is the link to a very good example on how to use ajax with php and mysql http://www.w3schools.com/php/php_ajax_database.asp