php echo from database with break lines - php

This is a simple question I believe, but can't figure it out yet.
I have a text area that after submit goes to a database, and then I echo this text on a page, but here is the problem, say the person writes on the textarea:
Hi Robert,This is just a test!.
Jason.
And the message goes to the database just like that, but when I echo that, I get:
Hi Robert, This is just a test!.
Jason.
This is the form:
<textarea name="newMessage" wrap="hard" cols="30" rows="3"></textarea>
<input type="submit" name="submit" value="Ingresar"> </>
This is the code I use to display the text:
<?php
while($row = mysql_fetch_assoc($messages)){
echo $row['mensaje']."<br/>";
}
?>
This is what I use to insert the code:
if(isset($_POST['submit'])){
$check4LB = $_POST['newMessage'];
while($letter = mysql_fetch_assoc($check4LB)){
if($letter=' '){
$letter='<br/>';
}
} /////I know this is not write bu is the idea i thgouht at least
$query = mysql_query("SELECT (ifnull(max(idRegistro),0) + 1) as id FROM messages");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$insertMessage = "INSERT INTO messages(idRegistro, mensaje) VALUES ('".$idMax."','".$letter."')";
mysql_query($insertMessage) or die(mysql_error());
echo "<meta http-equiv=Refresh content=\"0 ; url=".$_SERVER['PHP_SELF']."\">";
}

try echo nl2br($row['mensaje']);

Use nl2br() on the output from the database.

Try this
<?php
while($row = mysql_fetch_assoc($messages)){
echo str_replace("\r",'<br/>',$row['mensaje']);
}
?>

Related

MySQL not all results are shown

i have made i small membersearch for my site that looks for first name oder second name in my database. all members are inserted by the same way but i get not always a result back. if no member with a typed name is found than i get a message. that seams to work, but some times i get no message or if there are more than one results i get not all of them.
here is my code i use.
<form id="tfnewsearch" method="POST" action="admin_search_member.php">
<input id="tfq" class="tftextinput4" name="q" size="21" maxlength="240" value="Mitglied suchen..." />
<input type="submit" name="startsuche" value=" " id="tfbutton4">
</form>
and that's my query
if(isset($_POST['startsuche'])) {
$sql = "SELECT * FROM Mitglieder WHERE vorname LIKE '%".mysql_real_escape_string(trim($_POST['q']))."%' OR nachname LIKE '%".mysql_real_escape_string(trim($_POST['q']))."%'";
$result = mysql_query($sql) OR die("<pre>\n".$sql." </pre>\n".mysql_error());
$row = mysql_fetch_array($result);
}
if (mysql_num_rows($result) == 0) {
?>
<div id="body_box_tabs">
<div class="tabcontents">
<div id="view1">
<p style="color: #003137; font-weight: bold;">Das gesuchte Mitglied existiert nicht!</p>
<input class="button-link" type="submit" value="Zurück"/>
</div>
</div>
</div>
<?php
} else {
echo $_POST['q'];
?>
<div id="body_box_tabs">
<div class="tabcontents">
<div id="view1">
<?php
while($row = mysql_fetch_array($result)) {
echo "show me the found member";
}
}
?>
I hope some one can help me with this.
You're basically fetching and then discarding the first row of the query result. This will cause the "does not exist" message to be shown when there are no rows, will cause no output when there's one row returned, and will cause (n-1) outputs when n>1 rows are found. You will never see the first row of the result this way.
Either remove the first $row = mysql_fetch_array($result);, or change your loop:
do {
echo "show me the found member";
} while($row = mysql_fetch_array($result));
In this code block:
<?php
while($row = mysql_fetch_array($result)) {
echo "show me the found member";
}
}
?>
Do this:
<?php
while($row = mysql_fetch_array($result)) {
echo $row['field_name'];
}
}
?>
That should do the trick...

php form submit - Q2

i am sorry for the dummy question. Here is my simple PHP form with two SQL tables and with the ADD submit button I would like to move people from Test1 to Test2. Many thing are fine:( only the submit button does't work therefore no feedback from Test2 table.
Revised: Submit now works great
Q2 - still don't get the checkboxs to work:( - please
Could somebody show me how to track back such an error like this please?
<?php include("db_connect.php");?>
<html>
<head></head>
<body>
<form method="post" action="moving.php">
<table border="1">
<tr>
<td>
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1)) {
?>
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php } ?>
</td>
<td><input type="submit" id="add" name="add" value="Add" /></td>
<td>
<?php
$rigth='SELECT * FROM test2,test1 WHERE test2.collect=test1.id ORDER BY test1.name ASC';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2)) {
echo $resultb['id'] ;
echo "<br />";
}
?>
</td>
</tr>
</table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($i=0;$i<$count;$i++) {
$add_id = $checkbox[$i];
if ($add_id=='1') {
$sql = "INSERT INTO test2 (status, collect) VALUES(1, 1)";
$result = mysql_query($sql);
}
}
// if successful redirect to delete_multiple.php
if ($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=moving.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>
thanks:) from a beginner
where does $count come from?
Try using count($_POST['checkbox']) instead on your INSERT statement. Then you can iterate over the checkboxes using:
for ($c = 0; $c < count($_POST['checkbox']); $c++){
$checkbox = $_POST['checkbox'][$c];
...INSERT action...
}
In the sample code, you store the statement in a variable named $rigth, but you (try to) execute a statement stored in a variable named $right.
There are a couple things you can do to catch errors.
Try static code analysis; some tools can tell you if a variable is used only once (an indication it may be a typo).
Handle errors. Some functions return a special value if there's an error (False is a common one); for these functions, there is usually a related function that will return error information. Some functions will throw an exception; catch them where they can be appropriately taken care of. System error messages shouldn't be displayed to non-admin users so you don't disclose too much information.
Use an interactive debugger. For example, install the Xdebug extension on your development server (you do use a dev server, right?) and use an Xdebug compatible debugger.
the solution - not nice but it works - thanks for all the comments and help!!!
<?php include("db_connect.php");?>
<html>
<head>
</head>
<body>
<form method="post" action="test.php">
New:
<?php
$left='SELECT * FROM test1 ORDER BY name ASC';
$result1=mysql_query($left);
$count=mysql_num_rows($result1);
while($resulta = mysql_fetch_array($result1))
{
?>
<input name="checkbox_add[]" type="checkbox" id="checkbox_add[]" value="<? echo $resulta['id']; ?>"/> <? echo $resulta['name']; ?>
<br />
<?php
}
?>
</td> <td><input type="submit" id="add" name="add" value="Add" /><br /><input type="submit" id="delete" name="delete" value="Del" /></td><td>
<?php
$right='SELECT test2.id, test1.name FROM test2, test1 WHERE test1.id=test2.collect AND test2.status=1';
$result2=mysql_query($right);
while($resultb = mysql_fetch_array($result2))
{
?>
<input name="checkbox_del[]" type="checkbox" id="checkbox_del[]" value="<?php echo $resultb['id']; ?>"/>, <?php echo $resultb['id']; ?>, <? echo $resultb['name']; ?>
<br />
<?php
}
?>
</td></tr></table>
<?php
// Check if add button active, start this
if (isset($_POST['add'])) {
for ($c = 0; $c < count($_POST['checkbox_add']); $c++){
$checkbox_add = $_POST['checkbox_add'][$c];
$sql = "INSERT INTO test2 (status, collect) VALUES(1, ".$checkbox_add.")";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['delete'])) {
for ($c = 0; $c < count($_POST['checkbox_del']); $c++){
$checkbox_del = $_POST['checkbox_del'][$c];
echo date("Y-m-d");
$sql = "UPDATE test2 SET status='2', log='".date('Y-m-d')."' Where id=".$checkbox_del;
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
}
elseif (isset($_POST['new'])) {
$sql = "INSERT INTO test1 (status, name) VALUES(1, '".$_POST['newitem']."')";
echo $sql;
$result = mysql_query($sql);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test.php\">";
}
}
mysql_close();
?>
</form>
</body>
</html>

HTML/PHP Survey not passing to MySQL database properly

I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}

search mysql database

Please help, Im trying to search for mysql records using an html form to display the corresponding record for the entered primary key.
Here's my html form:
<td><input type="submit" name="Submit" value="Search"></td>
And here's the new.php form action:,
mysql_select_db("Hospital", $con);
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$_POST["fname"]}'");
while($row = mysql_fetch_array($result))
{
<input name="hnum" type="text" id="hospnum" value="<?php echo $row['HOSPNUM']; ?>" />
}
mysql_close($con);
?>
How do I get to display the hospnum in the html inputbox when I input the fname and then click the search button.
Note: This script, as-is, is vulnerable to sql-injections. The code that follows is not dealing with this, as it's out of the scope of the original question. Do not use this code as-is in a production environment.
You have a small problem jumping from PHP to HTML:
<?php
mysql_select_db("Hospital", $con) or die(mysql_error());
$fname = $_POST["fname"];
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$fname}'");
?>
<h3>Results:</h3>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<input type="text" name="hnum" value="<?php echo $row["HOSPNUM"]; ?>" />
<?php } ?>

PHP Update table Inserts blank fields

UPDATE: I narrowed it down, when I got rid of this tag in the header.php file it all works, can someone please explain this.
<script src="#" type="text/javascript"></script>
Hi I'm having quite an annoying issue with my php code. I am trying to update a php database, from a form, when I do this however the fields in the data base become empty after submitting. Please Help! You can view it in action here http://andcreate.com/shoelace/admin/edit1.php click on the lists on the right to edit them and see what happens.
<?php
include("header.php");
echo "<h2>Edit Posts</h2>";
echo "<div id='editNav'>";
echo "<p>Choose Post to Edit</p>";
//////////GET ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
$results = mysql_query("SELECT * FROM shoeData ");
while($row = mysql_fetch_array($results)){
$id = $row['id'];
$name = $row['name'];
$about = $row['about'];
echo "$date " . substr($name, 0, 40) . " <br/> ";
}
$thisID = $_GET['id'];
if(!isset($thisID)){
$thisID = 22;
}
//////////FINISH ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
echo "</div>";
///////IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
//has user pressed the button
$update = $_GET['update'];
if($update == "yes") {
$name = $_POST['name'];
$about = $_POST['about'];
$company = $_POST['company'];
$buy = $_POST['buy'];
//update data for this record
$sql = "UPDATE shoeData SET
name = \"$name\",
about = \"$about\",
company = \"$company\",
buy = \"$buy\"
WHERE id= $thisID";
$thisUpdate = mysql_query($sql) or die(mysql_error());
}
///////END IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
/////////// HERE WE GET THE INFO FOR ONE RECORD ONLY////////
$results = mysql_query("SELECT * FROM shoeData WHERE id=$thisID");
while($row = mysql_fetch_array($results)){
$name = $row['name'];
$about = $row['about'];
$company = $row['company'];
$buy = $row['buy'];
}
//////////////FINISH GETTING INFO FOR ONE RECORD ONLY/////////////
?>
<form name="formS" method="post" action="<?php echo $_SERVER['PHP_SELF']."?id=$thisID&update=yes";?>">
Name
<p>
<input type="text" name="name" id="name" value="<?php echo $name;?>" />
</p>
About
<p>
<input type="text" name="about" id="about" value="<?php echo $about;?>" />
</p>
Company
<p>
<input type="text" name="company" id="company" value="<?php echo $company;?>" />
</p>
Name
<p>
<input type="text" name="buy" id="buy" value="<?php echo $buy;?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" />
</p>
</form>
<p><a class="delete" href="delete.php?id=<?php echo $thisID;?>">Delete this post</a></p>
<?php
include("footer.php");
?>
You have $update = $_GET['update'];, but then right after that, you're using $_POST. A given request is either GET or POST, not both - thus whenever $_GET['update'] is set to "yes", there aren't going to be any POST vars set, and thus the update will be done with all of the values it's setting blank.
Chances are you actually meant to use either $_GET or $_POST in both places - since your updates are going through, but are blank, it sounds like you want to use $_GET (though for form submission/updates, you should probably really be using POST instead).
This may seem silly, but are you confusing $_GET and $_POST variables? You use one to check whether to enter the loop, and another to populate the string.
Also, as a minor aside, your SELECT statement towards the end of the snippet can be optimized by adding LIMIT 1 to the end of it, as presumably you're only going to be recalling one entry per id, no?

Categories