I have created a booking system which uses a clients username from their log in to auto populate a user name field when making a booking. I am not sure of how to get other information like their full name and ID from the database into these fields. Below is the code I have used to verify log in and store their username:
<?php
// Start up your PHP Session
session_start();
// If the user is not logged in send him/her to the login form
if ($_SESSION["Login"] != "YES_client") {
header("Location: login.php");
}
$username = $_SESSION["username"];
?>
I have also implemented the user name in the field using the following code:
echo "<input type='text' name='name' class='form-control' id='FullInputName' value=" . $username . ">"
Is there something simple I am missing? I have tried various methods to display the full data like using $row["Client_ID"] etc but could not get this to work for only the client who is logged into the system. My SQL statement is as follows:
"SELECT * FROM client WHERE Client_username= $username"
I would like to use the Client_ID in the select statement also to make it Unique. I have tried but got various errors.
Any help would be much appreciated!
EDIT
This is the code I have now tried to implement:
$query = "SELECT * FROM client WHERE Client_username='$username'";
echo $query;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['Client_username'];
}
But it is not working correctly - I am receiving this error:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Starting with your query i think is not correct.
If you are selecting a row and the type is a VARCHAR you need to add single quotes like this:
"SELECT * FROM client WHERE Client_username= '$username'"
Later you can read the results like
(pseudocode) while($row = mysqli_fetch_array) $row['Client_username']
something like that.
Tell me if this works for you
Related
M building a web app here.The authentication php code looks like this (Please ignore the threats for time being) :
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect('localhost','*****','******') or die(mysql_error());
mysql_select_db('cl29-demodb') or die(mysql_error());
$name=$_POST['name'];
$pwd=$_POST['password'];
if($name!='' && $pwd!='')
{
$query=mysql_query("select * from EmployeeTable where EmployeeName ='".$name."' and password='".$pwd."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
$_SESSION['id']=$res['id'];
header('location: profileindex.php');
}
else
{
echo "user name and password are incorrect" ;
echo "<a href=index.php> click here to go back </a>";
}
}
if(!isset($_SESSION['id'])){
echo "Sorry, Please login and use this page";
exit;
}
}
?>
I am able to login successfully and reach the profile of the user.But I want the profile to display only the information for respective users.The profile looks like this:
I have written the php to retrive the name,designation,weekly points,overall points,weekly rank and overall rank respectively.
I tried to echo the variables in the html.
But I am not able to do so.It isnot pulling any data.I have column for all the above fields in the table.
Kindly help.
May be this is the cause
mysql_fetch_row() return the numeric array and you are accessing as $res['id']
either replace mysql_fetch_row with mysql_fetch_array or try numeric index of your id
$_SESSION['id']=$res[0]; or $_SESSION['id']=$res[1];
use mysqli_fetch_assoc so you could call the columns by name if you are using mysql_fetch_array you should call the columns by their index no the by the column name.
There is no need to start a session again in the profileindex.php as the session has already started in the login page.
print the sql and run it in the backend to check if you are getting the desired result in order to further debug this.
I am trying to make an update form using PHP, getting my data from MySQL 5. I have the fields set as a TINYTEXT type. My problem is when I attempt to display a field in my form for editing, the display stops at the first space. For example: my database my have "John Doe" in one field, but when I attempt to display that field I only see "John". Here is a portion of my code:
$id =mysql_real_escape_string ($_GET['id']);
if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]', email='$_POST[email]', update_flag='$_POST[update_flag]', WHERE id='$id'";
mysql_query($UpdateQuery, $con);
}
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);
while($record = mysql_fetch_array($my_Data)) {
?>
<form action=listingupdate.php method=post>
<tr><input type=text name=business_name value=<?=$record['business_name']?> ></tr></br>
<tr><input type=text name=phone value=<?=$record['phone']?> > </tr></br>
<tr><input type=text name=fax value=<?=$record['fax']?> > </tr></br>
I have been googling several different ways, but I have not found what I am doing wrong. Would someone be so kind as to show my what I need to do to get all of the data in a field to display in my form?
Well a few things.. You should be using mysqli, not mysql since it is deprecated. Also you're calling mysql_real_escape_string on the id, but none of the other data so your script is wide open to SQL injection attacks. It looks like your code will fail if any of the posted data contains apostrophes. I'm not sure how you're planning to use GET and POST at the same time since your form, when submitted doesn't submit a GET value. With all that said, you should check the database to see if names are getting truncated in there, or if it's a client side issue.
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?
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...