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!
Related
My issue I believe is fairly simple but after a whole day trying different variations I have resorted to bothering you guys, please excuse me if this has been covered but I could not find a close enough example
I have a php file that is a processing file for a simple html form
Process.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host="1.2.3.4:3306"or die("wrong server"); // Host name
$username="username"or die("wrong Username"); // Mysql username
$password="password"or die("Wrong Password"); // Mysql password
$db_name="db-name"or die("wrong DB"); // Database name
$tbl_name="banned"or die("Wrong table"); // Table name
$member = isset($_REQUEST['member']) ? $_REQUEST['member'] : "";
// 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");
$find_member = mysql_query("SELECT member FROM banned WHERE member='$member'")or
die(mysql_error());
$ban = mysql_fetch_array($find_member);
if($member == $ban['member']){
echo ("this member is banned");
}
else {
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
}
?>
Form.html:
<form method="post" action="http://example.com/process.php">
<input type="text" name="member">
<input type="submit">
</form>
What im trying to accomplish:
A user would type their member number in the form.html and click submit, process.php will catch POST and either echo the text "this member is banned" or if member number is not on banned sql table, then display a html button with with a hidden input field that will carry the $member variable on to the next page
What is actually happening
no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button
Error reporting
php and sql error reporting displays no errors
Side note
DB structure
member VARCHAR(20) / id (auto increment) / Time (timestamp - defalt:current time stamp)
The member number is Alphanumeric and is max 15 characters
example: +ayw7394
The initial error of using:
if($member = $ban['member']){
was replaced with:
if($member == $ban['member']){
but produces the opposite effect of echoing the "banned member" message regardless of which number is being inputed
It seems as though the
if statements are being ignored
Can anyone please provide me with some advice?
thank you for your help so far
"no matter what number is entered into the form.html it always displays the html button. there is one number on the blacklist but when entered still displays the button"
The reason being is this:
In this if($member = $ban['member']) you're assigning = instead of comparing == to compare $member against the "member" row.
Change that to if($member == $ban['member'])
I must note that your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Footnotes:
</input> isn't a valid closing tag and can be safely removed.
Edit:
Also this code block:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' style='display:none;' value='<?php echo
htmlspecialchars($member);?'/>'
<button type='submit'>Continue</button>");
You're already in PHP, so there's no need for the <?php echo and ?>
Change it to:
echo ("<form method='post' action='http://example.com/access.php'>
<input type='text' value='".htmlspecialchars($member)."'/>
<button type='submit'>Continue</button>");
Which could explain why it shows "banned" because you're probably re-clicking on it after.
I suggest you just remove it and do a redirection instead.
Example, and by replacing it with the echo'd button:
else{
header("Location: your_form.html");
exit;
}
Your problem is at the line
if($member = $ban['member']){
This is actually always true because you are setting $member to be equal to $ban['member']. Did you mean ?
if($member == $ban['member']){
Echo $member and $ban['member'] to see if they are the same or different value.
Another step, other than guarding against SQL injection like someone else said, would be to run TRIM commands on your input and on your MYSQL fields to ensure spaces aren't an issue.
I have a website, mostly composed with public links, that is anyone can see them.
But I was thinking in creating some pages that could only be accessed by people who were registered on my website.
I looked around and found out that for that I would need a CMS, so I went to my host's CPanel to get one (DRUPAL) but instead of using what I already had, it simply created a new site.
By searching around people only want to know "how to integrate paypal with a membership site"...
Mine is supposed to be free; people join but don't need to pay for anything (at least for now) but some links can't be displayed to non-members.
I managed to get everything setup but I get an error...:
Warning: mysql_connect(): Access denied for user 'MYDATABASE_NAME'#'XXX.XX.XX.XX' (using password: YES) in /home/USERNAME/public_html/config.php on line 10
cannot connect to server
What's this? I have a few lines of code on the config.php
<?php
$host="www.triplestrata.com"; // Host name - my website
$username="MYDATABASE_USERNAME"; // Mysql username
$password="MYSQLPASSWORD"; // Mysql password
$db_name="MEMBER"; // Database name - I called my database MEMBER without the prefix
//Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
?>
This is right, Ya?
Use session variables.
With them, you can limit the entry to the page only when the session is occurring.
Make a login page, and then allow session start on all your pages, so the login follows.
Then, on the page you require, just add a clause that determines that only with the session started as a member, can one enter the page. If not, exit to mainpage or something.
Example:
<?php
Session_start();
if (!isset($_SESSION["lojamusica"]))
header("Location:errorlogin.php");
if ($_SESSION["lojamusica"]!="OK")
header("Location:errorlogin.php");
?>
In here, i am only allowing people with the session started, and connected to the database to enter my webpage, just need to pu this on top of the pages.
This is my loggin example, which came from a form on a previous page:
<?php
Session_start();
Session_destroy();
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("lojamusica");
$query = "SELECT username, password FROM login WHERE username='".$_POST["user"]."'";
$results = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($results);
if ($num == 0)
echo "Username not found!";
else {
$row = mysql_fetch_array($results);
if ($row["password"] == $_POST["pass"])
{
Session_start();
$_SESSION["username"] = $_POST["user"];
$_SESSION["lojamusica"] = "OK";
header("Location:mainpage.html");
}
else
header("Location:login2.html");
}
?>
This is the login page, simplified:
<form action="login.php" method="POST">
<label>Username:</label>
<input type="text" name="user" />
<label>Password:</label>
<input type="password" name="pass" /><br>
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
>
</h1></form>
To logout, simply reditect to a page like so:
<?php
Session_start();
Session_destroy();
echo "<script language='javascript'> window.top.location.href = 'login2.html'; </script>";
?>
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.
I’m trying to create a script for a user to enter in their username, and then have other logged in usernames randomly show, in a chatroulette fashion.
So, you will enter in your name and hit submit, then your name will be stored in a database and someone else’s name will be pulled out at random and shown. Then the user can hit a next button to see another random user name. When the user closes the page, their name will be unloaded from the system.
What I have tried is creating a simple post submission form which will return you to the same page logged in with your name, and it inserts your name into a mysql database. That worked.
Then I added some PHP code to detect that the name variable has been set and to find a random username in the database by finding the amount of users in the database and using a random integer to pick one out. I’m pretty sure it worked, however I was unable to get the user name to show with echo "$name";.
Then I tried adding an automatic logout by using:
<body onUnload=<?php session_destroy();?>>
That didn’t work. I didn’t get around to creating a next button because I was having a few problems, because I figured out that the logout wouldn’t work because I would be dropping rows from the database that wouldn’t be filled in again as new rows were added to the SQL database with an auto increment function causing blank pages to be shown.
Here is my code:
<html>
<head>
<title>random name</title>
</head>
<body>
<center>
<h1>random name</h1>
<h5>By DingleNutZ</h5>
</center>
<?php
if (!isset($_POST['name'])){
echo "<form action=\"index.php\" method=\"POST\" name=\"form\"><center><h4>name:</h4><input name=\"name\" id=\"name\" type=\"text\"/><br/>
<input type=\"submit\" name=\"submit\" value=\"Play!\"/></center></form>";
}else{
$name = $_POST['name'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ftr"; // Database name
$tbl_name="players"; // Table 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");
// To protect MySQL injection (more detail about MySQL injection)
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
session_register("name");
session_start();
if(session_is_registered(name)){
$players=mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand=rand(1,$players);
$callee=mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
echo "Logout";
if (isset($playing)){
if ($playing == 1){
$drop_name=mysql_query("DELETE FROM $tbl_name WHERE name=$name");
}}
}
}
echo "show random name here";
}
?>
</body>
</html>
There is a variable in there called $playing which was an attempt at a logout system.
I would be very grateful for any answers. Many thanks in advance.
as i didnt make it obvious (sorry guys) i need to fix my main problem which is being able to show a random user without ever showing a blank page due to the rows being dropped from the database. it is essential that usernames are removed from the system for privacy
You have a few issues in your code, not all are errors as such, some code is unneeded, other code is potentially dangerous.
$name = stripslashes($name); <<-- delete this line.
$name = mysql_real_escape_string($name); <<-- this is all you need.
mysql_real_escape_string() is all you need. No other escaping is need to protect against SQL-injection.
A few caveats apply, which I will discuss below.
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
Select * is an anti-pattern, never use it in production code. Explicitly select the fields you need.
You are using dynamic tablenames, I fail to see the need for this and it's also a dangerous SQL-injection hole.
Never use it but if you must, see this question how to secure your code: How to prevent SQL injection with dynamic tablenames?
You do the query, but you don't test if it succeeds, put a test in there:
$sql = "SELECT id FROM users WHERE name='$name' ";
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result);
$user_id = $row['id'];
}
else { do stuff to handle failure }
You are trying to get data out of the database, but this is not the way to do it:
$players = mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand = rand(1,$players);
$callee = mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
But I see a few issues:
Please stop using dyname tablenames, it is a really bad idea.
The return value of mysql_query is a query_handle, not the actual data you're quering.
I would suggest escaping all values, whether from outside or inside your code; I know this is paranoid, but that way, if you code design changes, you cannot forget to put the escaping in.
Never ever ever echo unsanitized data in an echo statement.
If you echo a $var, always sanitize it using htmlentities. If you don't XSS security holes will be your fate.
See: What are the best practices for avoiding xss attacks in a PHP site
rewrite the code to:
$result = mysql_query("SELECT MAX (id) as player_id FROM users");
$row = mysql_fetch_array($result);
$max_player = $row['player_id'];
$chooserand = mysql_real_escape_string(rand(1,$max_player));
//not needed here, but if you change the code, the escaping will already be there.
//this also makes code review trivial for people who are not hep to SQL-injection.
$result = mysql_query("SELECT name FROM users WHERE id = '$chooserand' ");
$row = mysql_fetch_array($result);
$callee = $row['name'];
echo "callee is ".htmlentities($callee);
Finally you are deleting rows from a table, this looks like a very strange thing to do, but it is possible, however your code does not work:
$drop_name = mysql_query("DELETE FROM $tbl_name WHERE name=$name");
As discussed mysql_query does not return values.
On top of that only a SELECT query returns a resultset, a DELETE just returns success or failure.
All $vars must be quoted, this is a syntax error at best and an SQL-injection hole at worst.
Technically integers don't have to be, but I insist on quoting and escaping them anyway, because it makes your code consistent and thus much easier to check for correctness and it elimiates the chance of making errors when changing code
Rewrite the code to:
$drop_name = $name;
$result = mysql_query("DELETE FROM users WHERE id = '$user_id' ");
//user_id (see above) is unique, username might not be.
//better to use unique id's when deleting.
$deleted_row_count = mysql_affected_rows($result);
if ($deleted_row_count == 0)
{
echo "no user deleted";
} else {
echo "user: ".htmlentities($drop_name)." has been deleted";
}
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