Only 1st letter of textarea going into database - php

Thanks to everyone who's given me such great advice over the last several months. I'm almost done with this project and I've learned so much. But I'm kinda stumped using textarea. I've googled and googled and can't find a solution.
This is not a public facing website so I'm not worried about sql injection and my organization uses an older version of PHP so I have to use mysql_query versus mysqli_query.
My problem is I have to echo two things from my database into a form so the user can edit and then update the database with the new inputs. One is a small string of text that I display using input="text". However the other is a longer string that lists a set of instructions so I'm using because it's too much for a text box. However when I run my update query only the first letter of the textarea string gets updated into my database. The textbox string works just fine. Here's my code
getrcs.php
<html>
<form>
<body>
<?php
$q = intval($_GET['q']);
include ('database_connect.php');
$sql= "SELECT * FROM RDS_REFERENCE WHERE ID = '".$q."'";
$query_result=mysql_query($sql);
?>
<table>
<tbody>
<?php
while($row = mysql_fetch_array($query_result)) {
?>
<tr>
<td>
<label>Sub File Series Number/Title</label>
<input type="text" style="width:250px;" required="Required" name="sub_fs_num_tle1[]" value="<?php echo $row['SUB_FS_NUM_TITLE']?>/>
</td>
<td>
<label>Disposition Instructions</label>
<textarea name="disp_instr1" cols="40" rows="30" style="font-family: Arial, Helvetica sans-serif; font-size: 12px;"><?php echo $row['Disposition_Instructions'] ?></textarea>
</td>
</tr>
<?php
}
?>
</tbody>
</form>
</body>
</html>
And update_rcs.php
<?php
include('database_connect.php');
foreach($_POST['id'] as $row => $id)
{
$sub_fs_num_tle1 = $_POST['sub_fs_num_tle1][$row];
$disp_instr1 = $_POST['disp_instr1'][$row];
$rcs_reference_update1 = "UPDATE RDS REFERENCE SET
SUB_FS_NUM_TITLE = '$sub_fs_num_tle1',
Disposition_Instructions = '$disp_instr1'
";
mysql_query($rcs_reference_update1) or die("Could not update".mysql_error());
}
header('Location:rcs_maint.php');
?>

Since your input is name="disp_instr1" the $_POST['disp_instr1'] is a string, not an array. This means that $_POST['disp_instr1'][$row] will output whatever character $row is in that string.
Simple demo:
$test = 'test';
echo $test[0];
Outputs:
t
Live Demo: https://eval.in/541463
To solve the issue use:
$disp_instr1 = $_POST['disp_instr1'];
Also SQL injections aren't the only reason to use parameterized queries. If a single quote needs to go to your db it will fail as is.

Related

MySQL AND Query Not Working From PHP File

This is really bugging me now as I've got this to work in phpmyadmin but can't get it to work from my php script.
The code below is a basic php file (I'm learning) where the user submits a part number and an order number in a form which is then passed to a query (via variables), and the query result is returned to a table in the same page.
I can get it to work fine when only passing the part variable $input, but when I pass the AND criteria, no results are returned. I have checked and checked again the table and the combination tested should work. I've tried hardcoding a part number and order number combination and the same happens (okay with just the part but not when you add the AND section). Testing this part AND order combination on phpmyadmin gives the desired effects. Have I missed something?
<?php include 'database.php' ; ?>
<?php
$input =$_GET['part'];
$ord = $_GET['order'];
// This query works fine with just the $input criteria but when I add AND 'Order' etc... it produces zero results.
$query = "SELECT * FROM `part_status` WHERE `Part` = '$input' AND `Order` = '$ord'";
$result = $conn->query($query);
$status = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Part Archive</title>
</head>
<body>
<!-- Form for submitting the two criteria of the query -->
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Part Number: <input type="text" name="part" value="<?php echo $part;?>" placeholder="Enter part number">
Order: <input type="text" name="order" value="<?php echo $order;?>" placeholder="Enter order number">
<input type="submit">
</form>
<header><h1>Orders For: <?php echo $input;?></h1></header>
<!-- Table for displaying the result of the slq query at the top -->
<table>
<tr><th>Part</th><th>Qty</th><th>Due Date</th><th>Order No.</th></tr>
<?php while($row = $result->fetch_assoc()) : ?>
<tr><td><?php echo $row['Part']; ?></td><td><?php echo $row['Qty']; ?></td><td><?php echo $row['Due Date']; ?></td><td><?php echo $row['Order']; ?></td></tr>
<?php endwhile ;?>
</table>
</body>
</html>
Always grateful for any pointers or suggestions.
Thanks #dbarthel for this solution...
I removed $status = $result->fetch_assoc(); and also the while loop replacing <?php while($row = $result->fetch_assoc()) : ?> and <?php endwhile ;?> with just <?php $row = $result->fetch_assoc()) ; ?> and this returned a record as requested in the form.
Thanks to all for your help and support. I can now move forward and try to develop this further.

Adding post values to database using mysqli

I seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.

UPDATE inside a WHILE statement

So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...

when i refresh the page the text removes by itself , php?

When I type something in a text box and save it in mysqli it works perfectly but when I refresh that same page the text that i wrote stuff, it disappears for no reason. I also I have another text box in that page and it works perfectly fine. How can I fix that? The bio text box is the one I'm having issues.
$getpro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));$pro = $getpro;
$bios = $pro["bios"];
$realtionship = $pro["realtionship"];
$impmessage = $pro["impmessage"];
if ($_POST['bio']){
$bio = $_POST['bio'] ;
$query;
}
if ($_POST['impmessage']){
$impmessage = $_POST['impmessage'] ;
$query;
}
$query = mysql_query("UPDATE `profile` SET bios ='$bio', impmessage = '$impmessage' WHERE username = '".$user_data['username']."'");<form name="bio"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="bio" rows="7" ><? echo $bios; ?></textarea><br />
<input type="submit" value="change">
</form><hr /><form name="impmessage"action="" method="post">
<p>Important Message</p> <textarea cols="50" style="resize:none" name="impmessage" rows="7" ><? echo $impmessage; ?></textarea><br />
<input type="submit" value="change">
</form>
I have rearranged & removed some of the code and tried tidying it a bit:
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) // if form is submitted using POST method
{
if ( isset( $_POST['bio'] ) ){
$bio = mysql_real_escape_string( $_POST['bio'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET bios ='$bio' WHERE username = '".$user_data['username']."'"); //update bios
}
if (isset( $_POST['impmessage'] ) ){
$impmessage = mysql_real_escape_string( $_POST['impmessage'] ); // escape special characters is user input
$query = mysql_query("UPDATE `profile` SET impmessage = '$impmessage' WHERE username = '".$user_data['username']."'"); //update impmessage
}
}
$pro = mysql_fetch_assoc(mysql_query("SELECT * FROM `profile` WHERE username = '".$user_data['username']."' "));
?>
<form name="bio" action="" method="post">
<p>Bios</p>
<textarea cols="50" style="resize:none" name="bio" id="bio" rows="7" ><?php echo $pro["bios"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
<hr />
<form name="impmessage" action="" method="post">
<p>Important Message</p>
<textarea cols="50" style="resize:none" name="impmessage" id="impmessage" rows="7" ><?php echo $pro["impmessage"]; ?></textarea>
<br />
<input type="submit" value="change">
</form>
Some notes for you:
First of all avoid mysql_* functions. Instead use mysqli or PDO
I would always prefer writing the code for processing of user inputs in the very beginning of the page, ie. before outputting anything. Because, if the user inputs makes any changes on the output, it would easily display the updates since we are doing the processing before outputting anything. So, when we query the db, it would fetch the updated data. Also, if we wanted to redirect to another page or have to send some other headers to the browser, we could do it, as the headers should always be sent before outputting anything.
Another thing is, always escape user inputs. Otherwise, prone to sql injections. Best thing would be to use prepared statements which is available in mysqli & PDO.
When you name id of elements in your HTML, make sure that it is unique. Because no same ids could occur twice. But class names can occur for any number of times.
Also make sure that your PHP code doesn't get mixed up with the HTML. Properly enclose the PHP code with the <?php & ?> tags. I would always prefer avoiding shorthands.
Since you are using two forms, both the input won't reach the server side. Only a single one. If you wanted to both inputs to be reached at the same time, then use a single form.
I have also avoided unwanted assignment operations from the fetched data, to other variables.
Also, you should always properly indent your code for better readability.
I hope this would help. Wish you good luck. :)
Looks like you're running your update query every page load. If the post value isn't filled and you refresh it's going to update with empty values.
Ps sberry is right lots of other things to fix before this goes production.

How do I post back to a database?

I am new to PhP and MySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.
Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.
Any suggestions or links to some examples will be much appreciated. Here is my code.
<form name="form1" method="post" action="">
<div align="center">
<?php
include("dbcon.php");
$query="select * from student order by year, studname";
$result=#mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)>0)
{
?>
<label>
<input type="text" name="txtyear" id="txtyear">
<input type="submit" name="btnyear" id="btnyear" value="Submit">
</label>
<table width="75%" border="1">
<tr>
<td align="center" width="20%"><strong>Student Number</strong></td>
<td align="center" width="27%"><strong>Name</strong></td>
<td align="center" width="23%"><strong>Course</strong></td>
<td align="center" width="30%"><strong>Year Level</strong></td>
</tr>
<?php
while($row=mysql_fetch_array($result))
{echo "<tr>";
echo "<td>".$row['studno']."</td>";
echo "<td>".$row['studname']."</td>";
echo "<td>".$row['course']."</td>";
echo "<td>".$row['year']."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
else
echo "no records found";
?>
</div>
</form>
You need a WHERE clause. A very basic example might look like this:
$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";
NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.
Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)
You can find more info about Mysql select query syntax on
http://dev.mysql.com/doc/refman/5.1/en/select.html.
Also don't use # for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (#mysql_query($query)) it seems it doesn't make sense anyway.

Categories