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.
Related
I'm working on a CMS site, I've got blog posts that I store in a database. I can create, edit and delete them. There's an issue though when I want to edit them.
I can't specify the WHERE clause in the update query to match the id of the blog post I'm trying to edit!
Suppose I've got a blog post with an id of '5'.
If I write this code for it, it works exactly the way it should.
$sqledit = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
But I don't want to edit just blog post #5, I want to edit the blog post that I'm updating. It seems to me this should work,
WHERE id= $_POST[id]";
... but it doesn't.
That just throws me an undefined id error. But it shouldn't because I can delete blog posts the exact same way with this particular code:
$sqldel = "DELETE FROM `paginas` WHERE id= $_POST[id]";
This does allow me to.
The code below is on the blog page, the edit query is in its own edit.php page
if (isset($_POST['edit'])) // if pressed, execute
{
echo
'<br><br> <div class="blogscript">
<form action="edit.php" method="post">Edit your stuff<br>
<input type="text" placeholder='. $pagetitle . ' ><br><br>
<textarea id="message2" name="message"><p>' . $message . '</p></textarea><br>
<input type="submit" name="editsubmit" value="Confirm" />
<input type="hidden" name="id" value="' . $id . '">. </form></div>';
}
I look forward to any tips I should try out.
EDIT:
This is my edit.php page
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "cmsbase";
$MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLi_CON->connect_errno)
{
die("ERROR : -> ".$MySQLi_CON->connect_error);
}
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $MySQLi_CON->error;
}
$MySQLi_CON->close(); //close connection
echo "<script>alert('Edited');location.href='index.php';</script>";
?>
EDIT: This is what the var_dump contains
In order for values to be present in $_POST, you need to have some element (e.g. <input>, <select>, <textarea>) inside your form with a name attribute set to the $_POST key you want.
You can add a hidden input to your form for id.
<input type='hidden' name='id' value='" . $id . "'>
Assuming you are getting the $message variable shown in that form code by selecting from your database, you should be able to get the id from there as well, or potentially from your $_GET if that is how you determine which post is being displayed.
(While this is not actually an answer, what I want to say does not fit in the comments)
Your line
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
Is horrific. This is the stuff of nightmares. Lets say that POSTed data in a form, is posted from a script from some robot somewhere, because I'm pretty sure you don't prevent XSRF in your code.
What if that script chose to post:
$_POST ==> array => message = "mwahahaha";
=> id = "1; DROP TABLE paginas;"
And you may think "how would they know my table name?" ,but that's easily found from other nefarious id inserts or other hacks on your code from other entry points which give a SELECT result, and many tables have common names such as "users" / "orders" / "baskets" / "touch-me" etc. (Ok well maybe not touch-me, but you get the idea).
Mysqli_real_escape_string() Could be used but thats only escaping quote marks and special characters, it does not mitigate SQL injection and compromise.
So, what should you do?
In this instance I want to draw your attention to PHP type juggling. Unlike many other languages, PHP has implied data types rather than specific data tyes, so a data type of "1.06" can be string and juggled to being a float as well.
Your id parameter in your MySQL is very probably a numeric integer value, so how can you be sure that the value of $_POST['id'] is also in integer rather than a SQL Instruction?
$id = (int)$_POST['id'];
This forces the value to be an integer, so
$id = (int)"1; DROP TABLE paginas;";
Is actually processed as $id = 1. Therefore saving you lots of compromised tables, spam rows and other nefarious rubbish all over your website, your database and your reputation.
Please take the following concept on board:
NEVER EVER TRUST ANY USER SUBMITTED CODE.
EVER
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
I just updated this question.
I can't seem to update my database whenever I am putting variable $ecode on my WHERE condition. But when I echo this variable it always echoes its right value.
<?php
require 'sqlicon.php';
$q=$_GET['q'];
$ecode= $_GET['ecode'];
echo"".$ecode;
$result=$db->query("UPDATE offset_form SET Approved='".$q."' WHERE Employee_Code='".$ecode."'");
?>
this is the content of sqlicon.php:
<?php
$db=new mysqli('localhost','root','',dbuser'); //localhost,username,password, dbname
?>
This is where I am getting the date for $q and $ecode: Sorry if it haven't been in mysqli yet.
testingjava.php:
<html>
<title> Offset Requests </title>
<head><link rel="stylesheet" type="text/css" href="up.css"/></head>
<script>
function Approval() {
var name;
name=document.getElementById('ename').textContent;
if(document.form1.approval[0].checked true) {
alert(name);
window.location.href = "sqli.php?q=Yes" + "&ecode=" + name;
}
}
</script>
<body>
<form id="form1" name="form1" method="post" action="testingjava.php">
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("dbuser",$conn);
$query=mysql_query("Select * from offset_form where Approved=''");
while($fetch=mysql_fetch_array($query)) {
$ecode=$fetch['Employee_Code'];
//$_SESSION['ecode']=$ecode;
$ename=$fetch['Employee_Name'];
$epos=$fetch['Employee_Position'];
$edpt=$fetch['Employee_Department'];
$dleave=$fetch['Date_Leave'];
$dreturn=$fetch['Date_Return'];
$reason=$fetch['Offset_Reason'];
echo "".$ecode ."".$ename." ".$epos." ".$edpt." ".$dleave." ".$dreturn." ".$reason;
echo "<input type='radio' name='approval' onChange='Approval()'>Yes";
echo "<input type='radio' name='approval'>No";
echo "<input type='text' name='remarks' size='30'>";
echo"<hr id='br'></hr>";
echo"<input type='submit' value='Submit' name='send' onClick='Approval()'>";
}
?>
</form>
</body>
</html>
I am only testing to manipulate my database when I triggered a radio button.
1) you should be using mysql_real_escape_string($_GET[]) or someone with inject a mysql command into you system like DROP TABLE which will be the end of your database.
2)secondly I would move over to using PHP PDO it is more secure and it is faster (by a long way).
3) change your scond to last line from
mysql_query($sql,$conn);
to
mysql_query($sql,$conn) or die(mysql_error()." _____is the string correct? ".$sql);
then is should echo out any errors, if you post the echoed error we can probably fix it
having looked at it I am guessing the problem is you have missed the .. around the $q, so the $sql contains the string "$q" rather than the string assigned to the variable $q
try this
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
try this way..
$sql=("update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
always try to echo your query and see what's going wrong with your query..
if password is set to your dbms the provide the third param passwrod
$conn = mysql_connect("localhost","root","<passwrod>");
or you can leave it blank if passwrod is not set.
and try this
$sql="update offset_form set Approved =$q where Employee_Code=$ecode";
or
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'";
note: double quotes will parse the php variable ,
most probably there is problem in the manner of quotes you are using.
are you should your query is what you want?
One thing that is confusing is the fact that you have this commented out:
"INSERT INTO offset_form (Approved) VALUES ('".$ecode."')"
And then you have this as your update:
"UPDATE offset_form SET Approved = '$q' WHERE Employee_Code = '".$ecode."'"
The values you are using don't tally together. Surely you should have:
"UPDATE offset_form SET Approved = '$q' where Approved = '".$ecode."'"
This is because you are inserting $ecode into the column Approved, but then searching for $ecode in another column called Employee_Code. Perhaps you need to modify your insert statement instead? Either that or $ecode could be just representing two different values at different times?
quotes
The only way switching quotes will make a difference is if your embedded values contain quotes themselves. In which case using the correct escape function will sort the problem. So you are free to use either:
"UPDATE offset_form SET Approved = '$q' where Approved='$ecode'"
or:
"UPDATE offset_form SET Approved = '".$q."' where Approved = '".$ecode."'"
or:
'UPDATE offset_form SET Approved = "'.$q.'" where Approved = "'.$ecode.'"'
but not:
'UPDATE offset_form SET Approved = "$q" where Approved = "$ecode"'
either of the first three should not make a difference.
further things to do
backticks
As a rule I always write my queries escaping table and column names using backticks, just to make sure I'm not accidentally using a reserved word:
"UPDATE `offset_form` SET `Approved`='$q' WHERE `Employee_Code`='".$ecode."'"
double check your dataset
Make certain that the same query you are trying to run in PHP, works inside your dbms. This involves echoing the query out in PHP and then executing it via PHPMyAdmin, Navicat, or whatever you use to access your database outside of coding. For example, a query with hard-coded values, if this doesn't work you have a logic problem in your query or database design that has nothing to do with PHP:
"UPDATE offset_form SET Approved='13' WHERE Employee_Code='12'"
check your white space
Sometimes queries that seem they should be working are having problems because your column values contain accidental invisible white space. If so, they would only be selectable using something like:
"UPDATE offset_form SET Approved='$q' WHERE Employee_Code LIKE '%".$ecode."%'"
check user privileges
Make certain your MySQL user has the ability to perform the type of query you are attempting, this means allowing SELECT, INSERT and UPDATE queries.
disclaimer
As others have already stated, you should upgrade to non deprecated database access methods. If not, you should at least be using mysql_real_escape_string to better protect against malicious intent.
Please debug the value of $q and try to run this code:
session_start();
$q=$_GET['q'];
$ecode=$_GET['ecode'];
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("asiantech",$conn);
echo"".$ecode;
echo"<br>".$q;
$sql="update offset_form set Approved ='".mysql_real_escape_string($q)."' where Employee_Code='".$ecode."'";
//$sql = "INSERT INTO offset_form (Approved) VALUES ('".$ecode."')";
mysql_query($sql,$conn);
I have a button on a webpage that allows users to add a video on that page to their list of favourites. behind this button is a form and some php. The PHP code uses a session variable to retrieve the username. This information is used to get the relevant user id from the database and store its value in a variable. Using the input value from the form it was possible to retrieve the tuple from the videos database table that related to the video in question and store the values of the video title and URL attributes in variables. The code then checks if the user has already added the video as a “favourite”. The favourites database entity is checked for tuples containing both the user id and video id. If both are contained in a single row of the database table the user has already added the video and is notified of this. Otherwise, the user id, video id, video title and URL are inserted into the favourites database entity and the user is informed that the video has been added
this all works fine in chrome or safari but does nothing in ie or firefox. The database is updated and message is displayed only in Chrome and safari. I've attached the code, please note the session has already been started in earlier code on the webpage. Any assistance would be greatly appreciated.
<div id="addfav">
<form action="python.php" method="post">
<input name="add" src="images/add.png" type="image"
value="3">
</form>
<?php
$user=$_SESSION['user'];
if ( isset( $_POST['add'] ) )
{
$vid = $_POST["add"];
$sql = "SELECT * FROM `users` WHERE username = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$uid= $row['user_id'];
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$url=$row['URL'];
$title=$row['Title'];
$check = mysql_query("SELECT * FROM `favourites` WHERE Uid = '$uid' AND vid_id = '$vid'") or die (mysql_error());
$r = mysql_num_rows($check);
if ($r>=1)
{
echo "already added to favourites";
echo '<script type="text/javascript">window.alert("Already added to favourites")</script>';
//'<span style="color: red;" />Already added to favourites </span>' ;
}
else
{
mysql_query("INSERT INTO `favourites` (`Uid`,
`vid_id`,`url`,`title`) VALUES ('$uid',
'$vid','$url','$title')")or die(mysql_error());
echo "Added to favourites";
}
}
?>
</div>
(Just a debug idea) Try to change your input image to a hidden element like this :
<form action="python.php" method="post">
<!-- I don't remove this, to keep the image shown-->
<input name="addimg" src="images/add.png" type="image" value="3">
<input type='hidden' name='add' value='3' />
</form>
Does it works now?
PHP is run server-side. This means that regardless of what browser you're using, it works as expected. The problem is definitely from HTML codes you've written if IE and Firefox can connect to your website without any problem.
I think the problem is inside your form tag because I think it's not standard you can either use a GET method inform that your form is submitted, or use a hidden input indicating it.
P.S. I think your code has security issues. (SQL Injection)
When user clicks on <input type="image" /> browser will pass coordinates of a click. Chrome will send three values:
add.x = x_coord
add.y = y_coord
add = input_value (3 in your case)
Note that in php you can access add.x/add.y value with $_POST["add_x"]/$_POST["add_y"] (see dot replaced with underscore)
At the same time, IE will not pass third value. That is why your if ( isset( $_POST['add'] ) ) will never return true. Option is to put video id value into some hidden field and use its name in that if.
You can easily check that behavior by doing var_dump($_POST); in php
PS:
You should never use values received in request without them being sanitized in sql queries. Right now code below is opened to sql injections:
$sql = "SELECT * FROM `Video` WHERE Video_id = '$vid'";
You should, at least, user mysql_real_escape_string function before value is inserted into a query:
$sql = "SELECT * FROM `Video` WHERE Video_id = '".mysql_real_escape_string($vid)."'";
And take a look at warning message on top of php manual page linked above: mysql_* functions are deprecated and you should better use PDO or mysqli extension.
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";
}