I am trying to send data from a textfield to my database. When I run the code I get no errors. But the code isnt posting the data to the database. I cant see whats wrong, can someone look what is wrong?
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<button name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
$data_1 = $_POST['data_1'] ;
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>
a) your script needs more error handling.
Before accessing $_POST['data_1'], you should test its existence, e.g. via isset().
Your database code doesn't have any error handling, too. Either set the error mode to PDO::ERRMODE_EXCEPTION or (/and) make sure you test each and every return value of the PDO::* methods.
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
if ( !$stmt ) {
yourErrorHandler('could not prepare statement', $db->error);
}
else if ( !$stmt->execute(array($adres_1)) ) {
yourErrorHandler('could execute statement', $stmt->error);
}
else if ( 1>$stmt->rowCount() ) {
// no record has been updates
}
else {
// at least one record has been updated
}
b) $stmt->execute(array($adres_1)); What is $adres_1? It's not anywhere else in that code.
c) Your code is prone to sql injections. You can fix that e.g. by using prepared statements + parameters.
The whole code looks like small parts of other scripts have been copy&pasted without understanding what those snippets do.
Are you using autocommit? maybe your db changes are being rolled back. Try adding an extra COMMIT SQL statement.
You have to submit your code. Then only the values are send to the php file by the POST method.
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<input type="submit" name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
if ($_POST['send']) {
$data_1 = $_POST['data_1'] ;
}
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>
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.
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 have two different directories on my wampserver, this code works on one, but not on the other, I don't understand why.
PHP
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$msg = "";
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUE ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
$msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
HTML
<form method="post" action="add_class.php">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
This is in the file "add_class.php" and I've tried many different things, putting single quotes (`) around the table columns in the $sql but still, it won't work. I've tried adjusting the names in the table, which had underscores but now have camelCasing, still made no difference. This code works perfectly in another directory, can someone please tell me why this is happening and possibly propose a solution? Thank you in advance.
P.S My connection works because I inserted a new row via phpmyadmin and looped through the database printing every existing "className" and it worked, I just can't insert from the php script.
connection.php
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
When asked if you've had assigned the sessions, you replied I assigned this when the user logs in. Moving forward from that, let's assume the assigned session as one written below:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$_SESSION['username'] = "HawqasKaPujaari";
$msg = "";
// this fails, as session is already set.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUES ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
echo $msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
<form method="post" action="">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
Note: The only changes I made were to change the action="" empty and changed VALUE to VALUES in your query.
connection.php:
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
As the above posted code seemed to be correct and was bugging me so I thought of testing it myself by creating the database/tables and it seemed to work properly without any errors. I have posted the relevant pictures below:
Note: Make sure you have the connection.php file in the same
directory as the add_class.php.
I am writing code that produces a <textarea> for a user to input something but it isn't giving me any output besides "please include some content" which is what it means to do if there is nothing in the box. This appears even if there is content in the <textarea> and won't even say "post fail" which is what it is meant to do if it can't insert into the database.
I am asking if anybody can see if there is something I have neglected to include, or if there is something that is wrong with my code.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$content = #$_POST['con'];
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
Try this code. It should work.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if(isset($_POST['con']) && $_POST['con'] != ''){
$content = #$_POST['con'];
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
You have a missing braces in your code
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
Should read
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
}
And
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") ) // <--- here
echo "post successful";
}else{
echo "post fail";
}
Making it readable also helps reduce errors
$query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')");
if ($query){
echo "post successful";
}else{
echo "post fail";
}
I see your code sends submited data to another page, i checked it through print_r($_POST)
I changed <form action="post.php" method="POST"> to <form action="" method="POST"> and tried and it was working, in case if the code you submited here is not "post.php" do this.
So it means someting is wrong with your insert query. So try this PDO way of inserting data.I thought of suggesting you the following easy pdo insert
$dbhost = "localhost";
$dbname = "mydatabase";
$dbusername = "root";
$dbpassword = "mypppasss";
//connection string
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
Inside the if($content) put the following code and try
$statement = $link->prepare("INSERT INTO post(userID,post_date,postContent)
VALUES(:inp1,:inp2,:inp3,:inp4)");
$statement->execute(array(
inp1=>$_SESSION["userID"],
inp2=>$post_date,
inp4=>$content
));
EDITED
Add this code to the form submitted page to see the posted data for debugging.
if($_POST){
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
EDITED
Note:# is used to hide errors, prevent it from displaying error
messages. that doesn't mean there is no error. Remove # for debugging
EDITED
Change your whole insert query part to this and try
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO post(userID,post_date,in_reply_to,postContent)
VALUES (".$_SESSION['userID'].",".$post_date.",'',".$content.")";
if (mysqli_query($conn, $sql)) {
echo "inserted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
This is what was wrong.
i had two set of <?php ?>, the first one in the code included require('connect.php'); within it, and the second one required it also.
<?php
require('connect.php'); <<<<<------ NEEDED TO ADD THIS
$content = #$_POST['con'];
$post_date = date("d-m-y");
$userID = mysqli_query($conn,"SELECT userID FROM users WHERE name = '".$_SESSION['name']."'");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$userID."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
So thats what i think the offending piece of code was. And it now will give me error saying the SQLI query was unnsuccessful, which means it is at least attempting that part, whereas before it was not.
Iam trying to create a private messaging system in which user sends message to another user and that content is inserted into database..Iam using a random number called hash to identify a conversation between two people..table for that is "message_group" and table for saving messages is "messages"..here comes the problem..
When I type something in text area and click on sendmessage button it inserts the data into the messages database..But if type something again and try to send it , the data wont enter into database..coz of this the other person is getting only first message..Please help me solving this problem..here's the code
<html>
<head>
<title>new convo</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'message_title_bar.php';?>
<?php include 'functions.php';?>
<div>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$my_id=$_SESSION['user_id'];
$user=$_GET['user'];
$random_number=rand();
$message=$_POST['message'];
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con=mysqli_query($connect,$query_string) or die(mysqli_error($connect));
if(mysqli_num_rows($check_con)==1){
echo "<p>Conversation already Started</p>";
}else{
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connect,"INSERT INTO message_group VALUES('$my_id' , '$user' , '$random_number')");
mysqli_query($connect,"INSERT INTO messages VALUES ('','$random_number','$my_id','$message')");
echo "<p>Conversation started</p>";
}
}
?>
Enter message:<br />
<textarea name='message' rows='7' cols='60'></textarea>
<br />
<br />
<input type='submit' name="submit" value="sendmessage" />
</form>
<?php
}
else{
echo "<b>Select User</b>";
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
$user_list=mysqli_query($connect,"SELECT `id`,`username` FROM `users`");
while($run_user=mysqli_fetch_array($user_list)){
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
Any help is appreciated.
<html><head><title>new convo</title></head><body>
<?php include 'connect.php'; ?>
<?php include 'message_title_bar.php'; ?>
<?php include 'functions.php'; ?>
<?php $connect = mysqli_connect('localhost', 'root', '', 'php_mysql_login_system'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); ?>
<div>
<?php
if (isset($_GET['user']) && !empty($_GET['user'])) {
?>
<form method='post'>
<?php
if (isset($_POST['message']) && !empty($_POST['message'])) {
$my_id = $_SESSION['user_id'];
$user = $_GET['user'];
$message = $_POST['message'];
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con = mysqli_query($connect, $query_string);
if (mysqli_num_rows($check_con)) {
$f_array = mysqli_fetch_array($check_con);
$hash = $f_array['hash'];
echo "<p>Conversation already Started</p>";
} else {
$hash = rand();
mysqli_query($connect, "INSERT INTO message_group VALUES('$my_id' , '$user' , '$hash')");
echo "<p>Conversation started</p>";
}
mysqli_query($connect, "INSERT INTO messages VALUES ('', '$hash', '$my_id', '$message')");
}
?>
<label for="message">Enter message:</label>
<textarea name='message' id="message" rows='7' cols='60'></textarea>
<br/>
<br/>
<input type='submit' name="submit" value="sendmessage"/>
</form>
<?php
} else {
echo "<b>Select User</b>";
$user_list = mysqli_query($connect, "SELECT `id`,`username` FROM `users`");
while ($run_user = mysqli_fetch_array($user_list)) {
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
There are many mistakes in code brother read basic first... and you are not using echo function to print old chat.
Just echo old chat. before post function.
steps:
1. Check if users already chatting.
2. If they are chatting echo chat which they already chatted.
3. If not chatting then start new chat.
4. if they are not chatting you dont need to echo anything just echo new message.
Your present code will just show you last message i think. because your page getting reload. and after it loads its just printing your last message in my view.. you need to print old chat as well.