My PHP page is not saving data - php

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')";

Related

MySQL PHP - Fetch data and present in HTML

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 delete the record from data base using php on which record i click

i am trying to create a crud.
i wrote php query to delete the fetched data . but i dont know what to write after ID= "" in Delete query. my code given below
index file
<html>
<head>
<title>crud system</title>
</head>
<body>
<?php include 'connect.php';?>
<form method="post" action="postdata.php">
username:
<input type="text" name="name">
<input type="submit" name="submit">
</form>
</body>
</html>
postdata.php
//postdata.php
<?php
mysql_connect('localhost','root','') or die("cannot to database");
mysql_select_db('users');
$name = $_POST['name'];
$sql="INSERT into add_data (name) values('$name')";
$query=mysql_query($sql);
if(!$query){
echo"data entrance failed".mysql_error();
}
else{
echo "data added successfully !";
}
?>
fetchint data select.php
<!DOCTYPE html>
<html>
<body>
<?php
include 'connect.php';
$result = mysql_query("SELECT * FROM add_data");
while($row = mysql_fetch_array($result)) {
echo $row["name"]."delete"."<br/>";
}
?>
</body>
</html>
delete.php
<?php
include_once 'connect.php';
mysql_query("DELETE FROM add_data WHERE **id=2"**);
header('location:select.php');
?>
now in delete file i dont want to write id=2 because it will only delete 2nd record i want to delete whatever i click on.
In select.php
while($row = mysql_fetch_array($result))
{
echo $row["name"].'Delete<br/>';
}
In delete.php
$del_id = '';
if(!empty($_GET['del_id']))
{
$del_id = $_GET['del_id'];
include_once 'connect.php';
mysql_query("DELETE FROM add_data WHERE id = '$del_id' ");
header('location:select.php');
}
Provide the id to the delete.php script and retrieve it with $_GET then perform your delete with a where clause using the retrieved id
echo $row["name"]."delete"."<br/>";
And in delete.php
$id = isset($_GET['id']) ? (int)$_GET['id']) : 0;

Form Data will not insert to database

I have connected my website to my database successfully when i submit the form it goes through but nothing is getting inserted into the database.
Code Below:
<?php
if( $_POST )
{
$con = mysql_connect("server","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buycruisesdb", $con);
$users_name = $_POST['name'];
$users_email = $_POST['email'];
$users_name = mysql_real_escape_string($users_name);
$users_email = mysql_real_escape_string($users_email);
$query = "
INSERT INTO `website_subscribers`(`name_sub`, `email_sub`) VALUES ([$users_name],[$users_email])";
mysql_query($query);
echo "<h2>Thank you for subscribing!</h2>";
echo $query;
echo $users_name;
echo $users_email;
mysql_close($con);
}
?>
buycruisesdb = database
website_subscribers = table inside the database
name_sub/email_sub = columns inside the table
the form html is below:
!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="php/subscriber.php" id="form" method="post" name="form">
<input id="name_sub" name="name" placeholder="Name" type="text">
<input id="email_sub" name="email" placeholder="Email" type="text">
<input type="submit" value="Submit" name="f_submit">
</form>
</body>
</html>
Not sure exactly why this is not inputing anyone have an idea?
it says that it is inserting the proper values and into the proper tables
Image
Square brackets are not valid in MySQL queries. You should be using quotes around the strings.
$query = "INSERT INTO `website_subscribers` (`name_sub`, `email_sub`) VALUES ('$users_name', '$users_email')";
change it to:
$query = "
INSERT INTO website_subscribers (name_sub,email_sub) VALUES ('".$users_name."','".$users_email."') ";
just copy the code and try it out

PHP line goes downwards after update to database

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.

How can i retrieve data from a textarea using PHP?

Given the following HTML form:
<form id="form1" name="form1" method="post" action="comments.php">
<textarea name="text" id="textarea" cols="45" rows="5"></textarea><br/>
<input type="submit" name="button" id="button" value="Update" />
</form>
...and the following PHP code (comments.php):
<?php
require("includes/config.php");
$fromtextarea = $_POST['text'];
$con = mysql_connect($dbserver, $dbusername, $dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname , $con);
$sql = "INSERT INTO textarea (comment) VALUES ('$fromtextarea')";
if (mysql_query($sql)) {
header("Location: home.php");
}
else
echo "no no no";
mysql_close($con);
?>
How can I get the data and display all user comments on a page?
Take a look at SELECT sql statement. Your query should look like something like this:
SELECT comment FROM textarea;
Then see how to manipulate the result with mysql_fetch_* functions in PHP (http://www.php.net/manual/fr/function.mysql-fetch-assoc.php).
By the way, mysql_* functions are deprecated (and will be deleted soon). I advise you using mysqli_* functions (http://www.php.net/manual/fr/book.mysqli.php) or (better) PDO (http://php.net/manual/fr/book.pdo.php).
Do like this
$sql = "INSERT INTO textarea (comment) VALUES ('". $_POST["text"] . "')";
Make sure you sanitize it before using it in your query.

Categories