So if i type text to my textbox, then I press submit button, wich sends data to update.php and update.php sends data to my database, then update.php redirects back to edit.php and the textbox whole text has gone downwards, any ideas ?
Edit.php
<html>
<head></head>
<body>
<form method="post" action="update.php">
Meist<br>
<textarea style="resize:none" cols="100" rows="10" method="post" type="text" id="meist" name="meist"><?php
include_once("connect.php");
$sql = 'SELECT meist FROM content WHERE id=1';
mysql_select_db('fava');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['meist']}";
}
mysql_close($conn);
?>
</textarea><br>
<input type="submit" value="salvesta"/>
</form>
</body>
</html>
update.php
<?php
// configuration
$dbhost = "localhost";
$dbname = "fava";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$meist =$_POST["meist"];
$id = 1;
// query
$sql = "UPDATE content SET meist=? WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($meist,$id));
echo "Edukalt salvestatud";
header('Refresh: 2; URL=http://localhost/php_sandbox/edit.php');
?>
If any questions then shoot, because it is kind of hard to explain.
For starters, get all that PHP code OUT of the content area. Since you are including the connect.php file, it is literally putting the contents of connect.php inside the textarea item. If there are new line characters in connect.php, like at the end of the file, it will create a blank line in the textarea input.
<html>
<head></head>
<body>
<?php
include_once("connect.php");
$sql = 'SELECT meist FROM content WHERE id=1';
$text = '';
mysql_select_db('fava');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$text .= "{$row['meist']}";
}
mysql_close($conn);
?>
<form method="post" action="update.php">
Meist<br>
<textarea style="resize:none" cols="100" rows="10" method="post" type="text" id="meist" name="meist">
<?php echo $text; ?>
</textarea><br>
<input type="submit" value="salvesta"/>
</form>
</body>
</html>
Note that I am created a blank $text variable and filling it with the data you want to have in the field and when all the work is done, we are echoing only that item in the content.
This cleans up the code, makes it clear what you are doing and makes sure stray new line characters are being implanted where you don't want them.
Related
I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
I want to insert multiple emails into the database using single text area.
This is my code :
PHP
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$dbhost = "localhost";
$dbname = "emails_test";
$dbuser = "root";
$dbpass = "";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $conn);
if(isset($_POST['submit'])) {
//$email = nl2br($_POST['email']);
$email = explode("\r\n", $_POST['email']);
foreach($email as $emails) {
$query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
if($query) { echo "Inserted into the database"; } else { echo"Fail, please try again"; }
}
}
HTML
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
I want table to be like this :
Use explode to get string into array by "\r\n"
don't use single quotes you need to use double quotes to explode the string by \r\n I just got to know that.
<?php
if(isset($_POST['submit'])) {
//$email = nl2br($_POST['email']);
$email = explode("\r\n", $_POST['email']);
foreach($email as $emails) {
$query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
if($query) {
echo "Inserted into the database";
} else {
echo "Fail, please try again";
}
}
}
?>
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea>
<br />
<input type="submit" name="submit" value="submit">
</form>
</body>
You may try this way
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea>
<br />
<input type="submit" name="submit" value="submit">
</form>
</body>
Note :- use "Enter" to put all email (one by one)
Insert into database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["submit"])) {
$str = $_POST["email"];
$email = preg_split('/\r\n|\n|\r/', $str);
foreach($email as $emails) {
$query = mysqli_query($conn, "INSERT INTO emails (email) VALUES ('".$emails."')");
if($query) { ?>
<script>alert("Inserted into the database");</script>
<?php } else { ?>
<script>alert("Fail, please try again");</script>
<?php } } }
mysqli_close($conn);
?>
Example :-
Your code will work as intended if you will just replace this
$email = nl2br($_POST['email']);
with this
$email = preg_split('/\r\n|\n|\r/', $_POST['email']);
The problem is, you just have replaced all \n\r with <br>\n\r. The nl2br returns a string with replacements, but you need an array for using it inside the foreach loop.
As an additional note, you're iterating through an array and every time you are adding this instruction:
<script>alert("Inserted into the database");</script>
If you will iterate through 10 emails, you will be alerted ten times in a row.
Also, mysql_query is deprecated. It's time to learn either PDO, or MySQLi, which will give you ability to use placeholders instead of unsafe direct injecting $_POST data into SQL query. Placehiolders are pretty easy to learn, and they can help you to build more reliable applications.
Do this in your code...
HTML
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea><br>
<small>Enter email IDs separated by comma(,)</small>
<input type="submit" name="submit" value="submit"><br>
</form>
</body>
PHP
if(isset($_POST['submit'])) {
$email = explode(',',$_POST['email']);//convert into $email array
$value = '';
foreach($email as $r) $value .= '("'.$r.'"),';//concatenate email for insert
$value = rtrim($value,',').';' //remove the last comma ;
$query = mysqli_query('INSERT INTO emails (email) VALUES '.$value);// insert all email in database in single query in different rows
if($query) echo 'Inserted into the database';
else echo 'Fail, please try again";
}
You will get your output...
Please see my code below.
How can I return the control to the index.php to an executable statement after the closing form tag to display query results on index.php page rather than code shown toward the end of processData.php?
I have searched through Google, this forum and have not seen a solution? Those familiar with Fortran, Visual Basic would appreciate the return statement that can be used to go back to the calling routine. Is there a statement similar to return to hand over the control to the calling web page in PHP?
Code for index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Report Summary</title>
</head>
<body>
<h1>Online Sales Report Demo
<br>
<br>
<form method="post" action="processData.php">
Enter Your Full Name:<input type="text" name= "author_name" />
<br>
Enter Your eMail Address:<input type="text" name= "author_email" />
<br>
<input type="submit" value="Submit">
</form>
**//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
</body>
</html>
Code for processData.php:
<?php
// define variables and set to empty values
$author = $email = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Next extract the data for further processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$author = test_input($_POST['author_name']);
$email = test_input($_POST['author_email']);
//Next echo the Values Stored
echo "<br>";
echo "<br>Your Name:".$author;
echo "<br>Your Email Address:".$email;
}
?>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydatabase');
$sql = "SELECT Sales_Author, Sales_Date, Sales_Channel, Sales_Title, Sales_Unit, Sales_Royalty, Sales_Currency
FROM Sales_tbl
WHERE Sales_Email= '" . $email . "' ORDER BY Sales_Date ASC";
$result = mysql_query( $sql, $conn );
if(!$result )
{
die('Could not fetch: ' . mysql_error());
}
?>
<table border="2" style="background-color: #84ed86; color: #761a9b; margin: 0 auto;">
<thead> <tr> <th>Date</th><th>Channel</th><th>Title</th><th>Units</th><th>Royalty</th><th>Currency</th></tr></thead><tbody>
<?php
while($row = mysql_fetch_assoc($result)){
echo "<tr>
<td>{$row['Sales_Date']}</td>
<td>{$row['Sales_Channel']}</td>
<td>{$row['Sales_Title']}</td>
<td>{$row['Sales_Unit']}</td>
<td>{$row['Sales_Royalty']}</td>
<td>{$row['Sales_Currency']}</td>
</tr>\n"; }
?>
</tbody></table>
<?php
mysql_close($conn);
echo "Fetched data successfully\n";
?>
</body>
</html>
If I take your question literaly this is one possibility:
In processData.php put that link where ever you want it to be:
back to index.php
then you can react on that parameter in index.php:
....
<input type="submit" value="Submit">
</form>
//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
<?php
if(isset($_GET['state'])) {
switch($_GET['state']) {
case "fromProcess":
echo "I come from process!";
// do whatever you want to do
break;
default:
echo "ERROR: undefined state submitted";
}
}
?>
</body>
</html>
There's of course also the possibility to redirect without clicking a link via
header("location: index.php?state=fromProcess");
// NOTE: This has to be before ANY output, and no output after that will be seen.
But I have the feeling, that you actually want to display data generated from processData in index.html.
Then you got at least two possibilities:
Include processData.php in index.php and wrap it in a
<?php
if(isset($_POST['author_name'])) {
include('processData.php');
// process the data and make output
}
?>
Same is possible the other way round (but that's kinda tricky for what you want to do).
One general thing you have to keep in mind:
php scripts are scripts, basicly all on their own.
They are out of memory once they finished executing, so you cannot call a function of another script unless you include it into the current script (without autoload - but that not what you want).
I'm new in PHP programming and I'm trying to create a PHP page that has a box to write a text, for example, store this information and exhibit it. The ideia is the user is going to write the text in the box and when the click to "Send" the MySQL will store the information in the table and the command "atualizaPagina()" will show the information added.
<!DOCTYPE html>
<?php
require_once("enviar.php");
if(!empty($_POST)){
gravaTopico($_POST["mensagem"]);
}
?>
<html>
<head>
<title>Teste em php</title>
</head>
<body>
<?php
atualizaPagina();
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<textarea rows="10" cols="50" name="mensagem"></textarea>
<input type="submit" value="Enviar" />
</form>
</body>
</html>
And the enviar.php file is here
<?php
function gravaTopico($values){
mysql_connect("localhost", "root", "Alabra%$") or die(mysql_error());
mysql_select_db("ifscjr") or die(mysql_error());
$strSQL = "INSERT INTO topicos(comentarios) VALUES($values)";
mysql_query($strSQL) or die (mysql_error());
mysql_close();
}
function atualizaPagina(){
mysql_connect("localhost", "root", "Alabra%$") or die(mysql_error());
mysql_select_db("ifscjr") or die(mysql_error());
$strSQL = "SELECT * FROM topicos";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)){
echo $row['comentarios'] . "<br />";
}
mysql_close();
}
?>
Try changing this:
$strSQL = "INSERT INTO topicos(comentarios) VALUES ('$values')";
MuthaFury is right.
But, also you need to check not only that $_POST ins not empty, you need to check that $_POST["mensagem"] exists (!empty($_POST) && isset($_POST["mensagem"])).
And you need to escape input string from quotes using mysql_real_escape_string, because if your $_POST["mensagem"] wiil contain quote (') your sql will be broken.
Example for your code:
$values = mysql_real_escape_string($values);
$strSQL = "INSERT INTO topicos(comentarios) VALUES('$values')";
I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly