This is the query:
if (isset($_POST['editMessage'])) {
$result = mysql_query("UPDATE messages SET message = '".htmlspecialchars($editedmessage)."' WHERE id = '".$id."'");
if ($result) {
die("<strong>Message has been edited!</strong>");
} else {
die("<strong>Error ".mysql_error()."</strong>");
}
}
Using this form:
<form action="index.php" method="post">
<textarea name='editedmessage' rows='5' cols='70'><?php echo $_POST['editedmessage'];?></textarea>
<input type='submit' name='editMessage' value='Edit'>
It's not showing an error, it updates the table field, but doesn't enter the edited message into the field, so the field updates and shows no informtion at all.
Where am I going wrong?
htmlspecialchars($editedmessage)
You don't seem to be defining $editedmessage anywhere, did you mean $_POST['message1']
That should really be mysql_real_escape_string( htmlspecialchars( ... ) )
Try the other way when its correct you get an ressource back:
if(!$result) {
die('Died: ' . mysql_error());
} else {
echo "Edited:";
}
You're missing the line:
$editedmessage = $_POST['editMessage'];
You are wrong here
$result = mysql_query("UPDATE messages SET message = '".htmlspecialchars($_POST['editedmessage'])."' WHERE id = '".$id."'");
You use $editMessage in the query instead of _POST[editMessage] (unless you have register globals on, apparently you don't).
However, do NOT do this without running mysql_real_escape_string() on editMessage first, and DO NOT run htmlspecialchars() on it! Encoded data does not belong in the DB.
Either do $editMessage = $_POST['editMessage'];, or use _POST in the query directly, but wrap it in mysql_real_escape_string() for goodness sake!
However, you DO want to run htmlspecialchars(), htmlentities(), or at the very least string_tags() on $_POST['message1'] when you echo it out. This page is XSS (cross-site script) vulnerable.
Related
I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.
Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.
my code
$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing
Please help me find out what's wrong. Hehe thanks in advance.
It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):
// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"];
First of all, you shouldn't use mysql_* functions anymore.
You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.
while ( $row = mysql_fetch_array( $edit ) ) {
printf( 'ID: %s', $row['id'] );
}
Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.
Carelessness again is the cause for all these. :) hehe
This is where the error is coming from
<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>
I have assigned a variable on a value with extra spaces/character? So the code must look like this.
<input type="hidden" name="idsend" value="'.$row['id'].'"/>
It must be assigned properly to work smoothly with the select statement.
I guess echo-ing the values isn't enough to see if there's something wrong.
Sorry for the trouble.
I'm having a big issue here, I'm trying to upload some data to a database, and I really don't have a clue why it isn't getting uploaded.
This one here is my HTML form to send data to the php. (This one here should have no problem at all)
<form method="post" action="uploadinfo.php">
<div style="width:542px;height:129px;margin-left:45px;margin-top:102px">
<textarea name="stufftoupload" placeholder="Write your stuff here" rows="8" cols="65"></textarea>
</div>
<div style="width:95px;height:29px;margin-left:489px;margin-top:22px">
<input type="image" src="myimg.png">
</div>
</form>
And this one here is my PHP to upload to the database, this is where the problem should be, but I have no clue what it is. I've tried several solutions, but nothing is working.
<?php
session_start();
$db = mysql_connect("host","db","pass");
if(!$db) die("Error");
mysql_select_db("table",$db);
$email = $_SESSION['email'];
$stuff = $_POST['stuff'];
if (!$stuff)
{
echo "<script type='text/javascript'>window.alert('Fill all the blanks.')</script>";
$url = 'upload.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
else
{
$url = 'success.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
mysql_query('SET NAMES utf8');
$sql = "SELECT * FROM table WHERE email = '$email'";
$result = mysqli_query($db,$sql);
mysqli_fetch_all($result,MYSQLI_ASSOC);
$sql = "INSERT INTO table SET stuff = '$stuff'" or die(mysql_error());
$result = mysql_query($sql);
?>
So this is about it, I'm almost positive it's something within this code, but it could be some bad session managing, though I'm not totally sure about it.
Anyway, thanks in advance for the help. It'll be totally appreciated.
$db is connecting to the database using the mysql method, but you are querying based on the mysqli methods. There are 2 things you need to do here to have an idea of what is going on. Firstly, change all your mysql_ calls to mysqli_ calls, and add some error reporting (so for example adding or die (mysqli_error($db); to the end of every line where you query) should point you in the right direction.
Your first glaring problem here is that you conneced to the DB using mysql_connect, but are then trying to query that connection using mysqli. Use one, not both.
Also, your SQL Query should read INSERT INTO table (stuff) VALUES ($stuff) rather than INSERT INTO table SET stuff = '$stuff'
There are a few problems here so I'll start with what I see now.
This line:
$db = mysql_connect("host","db","pass");
is what connects to your database and I'm assuming that "host" doesn't point to anything. Depending on where that is running, normally Localhost is used. You would also need to make sure the password is correct.
As suggested, use mysqli.
Your insert needs to be something like:
INSERT INTO table VALUES ({$stuff});
Not sure what you want from that form but your session variables will have to match the input names you use on the form.
$stuff = $_POST['stufftoupload'];
I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}
I tested the variables in the update statement and checked if a database connection is established, however the query doesn't run, can you please show me the error in my code.
for($i=0; $i <= $numcourses; $i++){
echo '<div class="new'.$i.'" id="new'.$i.'"><label>'.$course_names[$i].'</label>
<input name="edit'.$i.'" type="submit" value="Edit" /><input name="delete'.$i.'" type="submit" value="Delete" /><br /></div>';
$name="edit".$i;
if (isset($_POST[$name])){
echo '<input name="text" type="text" value="'.$course_names[$i].'" /><input name="save'.$i.'" type="submit" value="Save"/>';
}
$name2="save".$i;
if (isset($_POST[$name2])){
include "includes/open.php";
$newname=($_POST['text']);
$int=$i+1;
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
mysql_query($query) or die(mysql_error());
include "includes/close.php";
}
}
Update: Thanx Marc B, adding or die(mysql_error());showed me the error in my code, everything works again and I'm back on track.
You have no error handling on your query calls:
mysql_query($query) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
which would tell you if there's any problems with the query execution. On a meta level, you're wide open to SQL injection attacks, so you'd better read up about that and fix the problem before you go any further with your code.
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
is cID an integer ? in the update statement, looks to me like a string, try to echo every query and check the validity by executing it directly in your db
where do you connect to the database??
use mysql_connect(string hostname, string username, string password'); to connect to the database and then execute the query after selecting your database using mysql_select_db..
First you should remove the extra ; on $name="edit".$i;;
Then, how do you post the values? I see no <form> attributes in your code, hence it cannot be posted.
Also, everything is in a for loop. $newname=($_POST['text']); is never being set.
Maybe instead of this:
if (isset($_POST[$name2]))
try this:
if ($name2!="")
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.