I'm having an issue with the header("Location: index.php?action=messagesent") it will not redirect after The user presses submit and the php is ran. Normally it will redirect but for some reason it's not working, It just reloads the page after they hit submit. But it does echo "Message Sent" right under the header code. Any ideas on why it is not redirecting? Thank You in advance.
Heres my Code:
<form action="" method="post">
<div class="form-group">
<label for="message">Reply</label>
<textarea class="form-control" id="message" name="message" rows="5"></textarea>
</div>
<button type="submit" name="sendmessage" class="btn btn-purple waves-effect waves-light">Send Message </button>
</form>
</div>
</div>
<?php
$servername = "localhost";
$username = "myusername";
$password = 'password';
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO messaging
(fromid, toid, message, tousername,
fromusername,userprofile, sentdate, messagebefore)
VALUES (:fromid, :toid, :message, :tousername,
:fromusername, :userprofile, :sentdate, :messagebefore)");
// insert a row
$toid = $fromid;
$fromid = $_SESSION['user']['id'];
$messagebefore = $message;
$message = $_POST['message'];
$tousername = $row['fromusername'];
$fromusername = $_SESSION['user']['username'];
$userprofile = $row['userprofile'];
$sentdate = $date = date('H:i, jS F Y');
//Bind Inputs
$stmt->bindParam(':fromid', $fromid);
$stmt->bindParam(':toid', $toid);
$stmt->bindParam(':message', $message);
$stmt->bindParam(':tousername', $tousername);
$stmt->bindParam(':fromusername', $fromusername);
$stmt->bindParam(':userprofile', $userprofile);
$stmt->bindParam(':sentdate', $sentdate);
$stmt->bindParam(':messagebefore', $messagebefore);
$stmt->execute();
echo "Message Sent. ";
header("Location: inbox.php?action=messagesent");
}
catch(PDOException $e){
}
$conn = null;
?>
A header(Location: ...) will only work if you have not already sent output to the browser.
Earlier in your script you output the form, hence header() fails with an error message.
If you look in your error log, you will see the error message.
Add error reporting to the
top of your file(s) while testing right after your opening PHP tag for example
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now you will see the errors on the browser page.
Related
Whenever I tried to insert data to the table of database it keeps echoing "Connection successful" from connection.phpThe connection successful in my insert.php file
insert.php code
<?php
include_once("connection.php");
if(isset($_POST['Add'])){
$productCat = $_POST['category'];
$insertQuery = $pdo->prepare("INSERT INTO products_tbl (productCategory) VALUES (:ucategory)");
$insertQuery->bindParam(':ucategory',$productCat);
$insertQuery->execute();
echo "<script>alert('Successfully Register')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
?>
connection code
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "Ecommercedb";
try{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection success";
} catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
forms
<form action="insert.php" method="post">
<label for="">Product Category</label>
<input type="text" name="category" id="" placeholder="Category">
<input type="submit" value="Submit" class="btn" name="Add">
</form>
I tried removing the echo enter image description heresince it wasn't needed but it only lead to
HTTP:500 error.
I have also checked the connection and it is successful.
I expected there would be an alert saying it is successfully inserted but instead I keep getting the connection success from my connection.php
It looks like your code is working as intended, and the issue is likely related to the way you are submitting your form. The "Connection successful" message is being printed because your connection to the database is working, but the form data is not being passed to the insert.php script.
Make sure that you are correctly specifying the action attribute of the form element, and that the method is set to "post". Also, check that the name attributes of the form elements match the names of the variables in the insert.php script.
Additionally, you can try adding some debugging statements to the insert.php script, such as var_dump($_POST) or echo $productCat to check if the values are being passed to the script correctly.
This the connection using PDO
<?php
session_start();
include 'db_config.php';
try {
$conn = new PDO("mysql:host=localhost;dbname=$database","root","");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO users (name, username,
password)
VALUES (:name, :username, :password)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// insert a row
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$stmt->execute();
$query="select * from users";
$d = $conn->query($query);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This is the user registration form
<form method="post">
<div class="modal-body">
<div class="form-group">
<input type="text" name="username" placeholder="Enter Username" class="form-control">
<br>
<br>
<input type="text" name="name" placeholder="Enter Name" class="form-control">
<br>
<br>
<input type="password" name="password" placeholder="Enter Password" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="save_user">Save changes</button>
</div>
</form>
This is the Table
<tbody>
<?php foreach ($d as $data)
{
?>
<tr>
<td><?php echo $data['users_id']?></td>
<td><?php echo $data['username']?></td>
<td><?php echo $data['name']?></td>
</tbody>
</tr>
<?php
}
?>
This image is the User Registration Form
This image after clicking the Save button in my User Registration Form
This image after clicking the "reload button" in chrome
Hello Everyone, How to fix this kind of error. The Scenario is if the Admin wants to register another user so that the admin is going to click the button for the user registration form once the admin clicked the button the admin need to fill out the form then once the admin finishes the form then click the SAVE button to save the data in "IMAGE "2". Imagine the data is saved so that when the user clicked the reload page in chrome the Previous data duplicates "IMAGE 3". How to prevent this? Sorry, I'm Beginner in PHP :)
In your place I would not put all pdo queries in one pile like this because it is going to run every time you load the page. Add triggers to them as clearly you want these queries to run only when you click save button.
Instead separate your queries you can do something like this. I can see you already load file db_config.php so why configure db again ? Feel free to use below as an example.
db_config.php
$host = 'localhost';
$db = '';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new \PDO($dsn, $user, $pass, $opt);
Now every time you load this file you have a connection to database.
So you can do something like this.
<?php
session_start();
include 'db_config.php';
if (isset($_POST['save_user'])) {
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
//Your sql query
$sql = "INSERT INTO users (name, username, password) VALUES (:name, :username, :password)";
// prepare sql and bind parameters
$stmt = $conn->prepare($sql);
//Set your parameters
$params = ['name' => $name, 'username' => $username, 'password' => $password];
// insert a row
$stmt->execute($params);
}
function loadUsers()
{
$query = "SELECT * FROM users";
$d = $conn->query($query);
}
loadUsers();
My form for collecting visitors' mails for newsletter is not sending information to my database, instead just adding spaces with index adding up with no data
this is my html code
<form action="php/newsletter.php" method="post" >
<div class="input-group">
<input class="form-control" type="text" id="email" name="email" placeholder="E-mail ... ">
<span class="input-group-btn">
<button class="btn btn-primary subscribe" type="button" value="insert"><i class="pe-7s-paper-plane pe-2x"></i></button>
</span>
</div>
<!-- /input-group -->
</form>
and this is the php
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO subscribers (email)
VALUES ('$email')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Request sent successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
where could my mistake be?
You haven't defined $email in your PHP script. Also, you should use a prepared statement for queries with user inputs, to prevent SQL injection (http://bobby-tables.com) -> This is kinda important, please read about SQL injection. Its one of the biggest security issues with PHP websites and it allows 3rd persons to delete your whole database in a few seconds.
Also, to access data posted from a form, you always access the $_POST array, while the key ["email"] is the name of the input.
Try this code:
<?php
$servername = "localhost";
$username = "pridedri_news";
$password = "BBIT/7949/1/1630";
$database = "pridedri_NEWSLETTER";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare("INSERT INTO subscribers (email) VALUES (:email)");
$sql->bindParam(':email', $_POST["email"]);
// even exec() returnes true or false!!!!
if($conn->exec($sql)) {
echo "Request sent successfully";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//$conn = null;
?>
<Doctype! html>
<body>
<a href="http://pridedrivetours.co.ke/">Back</>
</body>
</html>
Declare $email before using it in mysql query
$email = $_REQUEST['email'];
I hope it will work for you
This problem is really giving me a hard time. I have 4 files, one for DB config, the other for login page, 3rd for login-processing and lsat one for the redirect after successful login)
This is my db-connect.php:
<?php
$servername = "localhost";
$username = "dbroot";
$password = "dbpassword";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
the form in my user-login.php:
<form action="includes/login-process.php" id="login" class="formoid-metro-black" style="background-color:transparent;font-size:14px;font-family:'Open Sans','Helvetica Neue','Helvetica',Arial,Verdana,sans-serif;color:#FFFFFF;max-width:400px;min-width:150px; float:right;" method="post" enctype="multipart/form-data"><div class="title"><h2>Log In</h2></div>
<div class="element-input"><label class="title">Username<span class="required">*</span></label><input class="large" type="text" name="username" required="required"/></div>
<div class="element-password"><label class="title">Password<span class="required">*</span></label><input class="large" type="password" name="password" value="" required="required"/></div>
<div class="submit"><input type="submit" name="submit" value="Log In"/></div></form><script type="text/javascript" src="forms/sign-up-form_files/formoid1/formoid-metro-black.js"></script>
The login-process.php:
<?php include ("db-connect.php");
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$encrypt = md5($password);
$userquery = "SELECT * FROM user WHERE `user-username`='$username' AND `user-password`='$password'";
$run = mysqli_query($conn,$userquery);
if(mysqli_num_rows($run)>0){
$_SESSION['username']=$username;
?>
<script>alert('Login successful.')</script>
<script>window.open('../user-profile.php','_self')</script>
<?php
}
else {
?>
<script>alert('Username or Password Incorrect.','_self')</script>
<script>window.open('../user-login.php','_self')</script>
<?php
}
}
?>
And in my login page, after i successfully log in, proven by the script alert being successful, however, as the user-profile.php opens (where I put a session_start() on top), it directly runs the condition inside the if statement, ignoring the fact that i already successfully logged in.
This is my user-profile.php:
<!DOCTYPE html>
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<script> alert('Please Log-in first.','_self')</script>
<?php include_once('user-login.php');
}
else {
$first_name= $_SESSION['fname'];
$first_name= ucfirst($first_name);
?>
//rest of my code
The code above should run what's inside the else statement, but instead i keep getting the alert to login first. (Just ignore the $firstname codes, I want to get it for output below). Does any of you have any idea about this? If so, pleeeease help me. Thank you!
In your login-process.php, you must session_start() first before setting values to session variables.
you are accessing session directly without declaring the session. User session_start() before accessing session variables and you may use session_close() once you are done accessing them.
I'm trying to confirm if a user submitted valid credentials.
HTML
<form action="assets/php/account/login_user.php" method="post" id="login" class="center">
<div id="register_errorloc"></div>
<div class="form-group">
<input type="text" name="login_username" id="login_username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" name="login_password" id="login_password" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="submit" value="login" id="submit_login" class="btn btn-success form-control"/>
</div>
</form>
PHP
$username = trim($_POST['login_username']);
$password = hash('sha512',trim($_POST['login_password']));
//to check if values are correct by myself
echo '<br>' . $username . '<br>' . $password . '<br>';
include_once '../../../assets/php/DB/DBConnect.php';
//check if valid credentials are entered
$stmt = $conn->prepare("SELECT * FROM tbl_users WHERE username = ?");
echo $stmt->bind_param('s', $username);
echo $stmt->execute();
echo $stmt->store_result();
if($stmt->num_rows == 1){
echo 'Good Creds';
}else{
echo 'Bad Creds';
}
When I'm doing this it always shows 0 results. When I change the querystring to
$stmt = $conn->prepare('SELECT * FROM tbl_users WHERE username = "abc"');
I get the result I'm looking for. I'm confused because I'm using the same approach on a different page and it's working like a charm.
Screenshots
Login form
Submitted form
Row I'm looking for
Edit: Added all code.
Edit2: Added screenshots
Edit3: Added Form HTML
Edit4:
Nothing is wrong with the form submit. When I'm hardcoding the variable like this:
$username ='abc';
It still doesn't work
I'm sorry but you posted screenshots that don't help us.
In order to avoid further commenting, am submitting the following.
Your form and its related elements may be failing and require a POST method and that name attributes exist for each of them.
I.e.:
<form method="post" action="???">
<input type="text" name="login_username">
...
Edit:
Try the following, comments are getting too extensive:
$check = $conn->prepare("SELECT * FROM tbl_users WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();
$row_chqry = $check->num_rows;
if($row_chqry > 0 ) {
echo "Exists";
$check->close();
$conn->close();
}
Edit #2:
OP posted an answer stating that they were using the same variable for their db connection.
Something I would have spotted right away and causing a conflict, had full code been posted. I've seen that happen quite a few times before, and remember posting answers for them too. As to where they are exactly, it would take some time for me to find them; but I do remember posting answers for related questions.
Oh well, problem solved.
Solutions:
Use a different variable for your username(s).
Use unique variables.
I finally found the error:
When connecting to my DB I use:
$servername = "";
$username = "";
$password = "";
$db = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In my submission script I also use $username. Including the DBconnection file caused my local variable ($username that I get from the form) to be overwritten with the username found in the DBconnect.