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
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'm trying to make a simple auction website. I need to keep track of the user that adds items to the auction. I've figured out how to store the user's account id and I thought storing the username would be similar, but I am unable to work it out. No matter what I've tried, the username is never stored in my items table.
This is my additemprocess.php page.
<?php session_start(); ?>
<html>
<head></head>
<body>
<?php
require_once("dbconnect.inc");
$_SESSION['username']=$_POST['username'];
$item=$_POST['item'];
$description=$_POST['description'];
$accountid=$_SESSION['accountid'];
$sql= "INSERT INTO biditems (username, accountid, biditem, biddesc) VALUES
('{$_SESSION['username']}', '$accountid', '$item', '$description')";
$result=mysql_query($sql) or die("Error in adding item: " .mysql_error());
$mess="Item successfully added!";
echo $mess;
?>
And here is the page that should list the items, showing the username of the user that added the item.
<?php
session_start();
require_once("dbconnect.inc");
require_once("checkstatus.inc");
$sql=" select * from biditems";
$result=mysql_query($sql);
echo "Items for Auction";
while($row=mysql_fetch_array($result)) {
$itemid=$row['itemid'];
$item=$row['biditem'];
$auctionby=$row['username'];
$description=$row['biddesc'];
echo "<p>$itemid $item $auctionby $description</p>";
}
?>
Here is my code to add an item.
<?php
session_start();
require_once("dbconnect.inc");
?>
<form id="additem" name="additem" method="post" action="additemprocess.php">
Item<br>
<input type="text" name="item" id="item"/><br>
Description<br>
<textarea name="description" id="description"></textarea><br>
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
You are currently using $_SESSION['username']=$_POST['username']; but you need to treat this username like the accountid. It should have been stored when you login in a session, then recalled when you enter the bid data in its database.
So for example:
On login :
$_SESSION['username']=$_POST['username'];
And on storing the bid:
$username = $_SESSION['username'];
or alternatively get the username from the users table using the accountid then add it to the query that way like:
$username = $row['username'];
Additionally, if you tried this but had trouble sharing this data between pages using sessions, then make sure you are including session_start(); on the top of each page where you are going to use sessions.
The problem is at: $_SESSION['username']=$_POST['username'];, you're setting a session to a post which doesn't even exist..? Set the $_SESSION['username']; in the process of logging in.
So on the spot where you are setting the $_SESSION['accountid'] equal to the ID of the currently logged in account using something like: $_SESSION['accountid'] = $row['id'];.
Right under there you'll add $_SESSION['username'] = $row['username'];.
Then just delete the $_SESSION['username'] = $_POST['username']; at your adding item process.
ANOTHER NOTICE: Do not use MySQL anymore since it's deprecated in versions of PHP5 or higher due safety reasons. Try using MySQLi (MySQL improved or PDO): php.net/manual/en/mysqlinfo.api.choosing.php
Beginner here.
The issue I am facing is getting rather tedious now despite me doing this a hobby, I have been stuck at this point for the last few days and have tried searching everywhere for a solution.
I have even completely reworking the code I have, following other examples/tutorials.
This is the closest I get to.
Everything is filled out, form submitted. It states successful but when I return back to the page, the field hasn't been updated. I have even checked the database directly to ensure the output display isn't wrong. But it doesn't appear there either.
(I do have other entries in the table, but I only want this page to edit one of them).
Any help pointing me to my error and why would be greatly appreciated. Best to learn where I have gone wrong so I can look out for it in the future.
<?php
$host="****"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id from the address bar
$id=$_GET['id'];
// get value of modname from the form
$modname=$_POST['modname'];
// update data in mysql database
$sql = "UPDATE $tbl_name SET modname='$modname' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>Return to overview</a>";
}
else {
echo "ERROR";
}
?>
The page with the form.
<?php
$host="****"; // Host name
$username="****"; // Mysql username
$password="****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="****"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
// Retrieve data from database
$sql="SELECT modname FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<form name="form1" method="post" action="update_ac.php">
<input name="modname" type="text" id="modname"></td>
<br>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
In this case, your query is solid and syntax is correct, but your variables don't contain the values you are expecting. Since you are learning, I'd like to offer some advice and example code.
While your code is still somewhat simple, change to the mysqli API. The syntax is similar but it is not depracated like mysql and you can use prepared statements.
When in the development stage, always turn on error reporting for your functions/conditions.
ALWAYS be sure to verify that your variables contain the values you are expecting before you try to use them with isset(), empty(), etc.
Always validate/sanitize/escape user input before inserting into your database.
Sample:
So it seems you are getting the id from a query string initially, such as http://domain.com/get_id.php?id=1? If so, your code should work, just make sure your URL is formed properly. If you are getting the id here from your <form>, then it should be $_POST instead.
// get value of id from the address bar
if(!empty($_GET['id'])) {
$id=$_GET['id'];
} else {
echo "ID is empty";
}
// get value of modname from the form
if(!empty($_POST['modname'])) {
$modname=$_POST['modname'];
} else {
echo "ID is empty";
}
// update data in mysql database
$sql = "UPDATE $tbl_name SET modname='$modname' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='edit.php'>Return to overview</a>";
}
else {
echo mysql_error();
}
On your form, you need to select the id before you will be able to echo it.
// Retrieve data from database
$sql="SELECT id,modname FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<form name="form1" method="post" action="update_ac.php">
<input name="modname" type="text" id="modname"></td>
<br>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
Even though your id field is a hidden field in your form it is still sent as a POST attribute, so you need $_POST['id'] to retrieve the value (not $_GET['id']).
Also, you should put table and column names in ` commas, like this;
$sql = "UPDATE `$tbl_name` SET `modname`='$modname' WHERE `id`='$id'";
However, your code is also wide open to SQL injection. Read this question and rewrite your code.
This should fix your issue.
$sql = "UPDATE {$tbl_name} SET modname='{$modname}' WHERE id='{$id}'";
Hope it helps!
I’m pretty much a complete beginner when it comes to PHP and have been having some problems with my script to update the current users values in the database – when the script fires it doesn’t update the value in the database as intended at all.
Some background info:
Database name: “user”
Table “users” with columns User ID , Username , Password , Emailaddress , Offer.
Site that I’m working on allows users to complete a number of offers and then get rewarded upon completion. The offer column has the default value of “1”. Upon login the user is redirected according to the value in the offer column. (So on first login user is redirected to example.com/offer1 , after offer 1 is completed this value is updated so on next login user is redirected to offer 2 – in essence storing the users progress) This login process works fine , its just updating the value which is my problem.
This is the script which is played after an offer is completed (in this case after offer 3 is completed) – aim to connect to database and then update that users “offer” so when they next login they will be directed to the correct offer – thus storing their progress:
~Could this actually not be a problem with the Script its self but in regards to sessions not starting/continuing correctly upon login – or maybe an issue with the script not using the session data correctly?~
<?php
session_start();
$con = mysqli_connect("localhost","name","password","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM user WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
header("location: http://example.com/offer4".$plus);
?>
The mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" ); isn't working at all, could the issue be here?
In case it helps , this is a previous version I was using which did work in updating the values but does so for all users in the database rather than just the one user who is logged in. So lets say Jim has completed this offer , his Offer value will be updates to 3 but so will all the other users will have their offer value set to 3 when only Jim’s should be.
<?php
session_start();
$con = mysqli_connect("localhost","username","pass","user");
$select = mysqli_fetch_assoc(mysqli_query($con,"SELECT offer FROM users WHERE Username = '".$_SESSION['username']."'"));
$plus = $select['offer']++;
mysqli_query($con,"UPDATE users SET offer=3".$plus);
header("location: http://example.com/offer4".$plus);
?>
Just for reference here is my login script – this works correctly in redirecting user upon login to value in their Offer column (could my problem be to do with sessions not starting correctly?)
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo '<meta http-equiv="refresh" content="0;URL=\'http://example.com/offer'.$row['offer'].'\'" />';
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
Lastly, heres base.php
<?php
session_start();
$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "user"; // the name of the database that you are going to use for this project
$dbuser = "name"; // the username that you created, or were given, to access your database
$dbpass = "password"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
Thank you very much for your time and have a good evening ; very much appreciate all the previous replies here that have been so helpful.
Try this:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start();
if(!empty($_SESSION['Username'])) {
$con = mysqli_connect("localhost","username","pass","user");
$username = mysqli_real_escape_string($con, $_SESSION['Username']);
$result = mysqli_query($con, "UPDATE users SET Offer = Offer + 1 WHERE Username = '{$username}'");
while ($row = mysqli_fetch_assoc($result)) {
$offer = $row['Offer'];
}
header("Location: http://example.com/offer".$offer);
} else {
echo "You are not logged in.";
}
mysqli_real_escape_string will escape dangerous characters from the username. You can use an UPDATE to increment a cell's value by an amount (in this case 1).
Another thing to note: In the PHP on the page with the HTML, you are using mysql extension functions instead of mysqli. The mysql extension is deprecated. Either way, your code is inconsistent in the use of mysql and mysqli. For a list of equivalent mysqli functions, check the PHP manual.
You said your database was called user and your table users. In your first query statement, you selected offer from a table called user not users. You can use mysqli_error() to display errors, which you would have received.
Regarding your second mysqli_query statement:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
There is no $id anywhere else in your code. Also you need a space before your where, otherwise if $plus == 13, the statement reads SET offer=313where user_id....
According to your code ($select['offer']++), you retrieve the previous offer value, increment it by 1 and then set the offer value in the database to this incremented value with a 3 added on to the beginning.
If offer == 31, then after going through your code, the new offer == 332.
EDIT: Something else I just noticed. I think you are misunderstanding the ++ operator. When used after an operand, it is called the post-increment operator. When used before, it is called the pre-increment operator. The reason for this is because in the case of the post-increment operator, the value of the operand (in your case $select['offer']) is assigned to $plus before it is incremented. What this means, in the context of your code, is that you are never actually incrementing the offer value.
I think the problem is with this line:
mysqli_query($con,"UPDATE users SET offer=3".$plus."where user_id = $id" );
Where is $id coming from? In the line above, you used username.
Your SQL is "UPDATE users SET offer=3".$plus."where user_id = $id". In PHP with $plus variable equal, e.g. "54" this becomes "UPDATE users SET offer=354where user_id = $id". So, a space is missing before where.
If this is not the case, learn to use mysqli error logging: http://php.net//manual/ru/mysqli.error.php.
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.