Use of header function in PHP - php

I'm adding a contact to my database with a form on the page add.php, the INSERT code for this form is on another page we'll call php.php page. In php.php I have a header function which I would like to have redirect the user to another page edit.php?ID=100, ID=100 being the contact that was just entered. How would I do this, do I need to do a fetch from the db before the header function and INSERT query?
<?php
if (isset($_POST['$fname'])) {
header("location: http://www.mydomain.com/contacts/edit/?ID=<? echo $row['ID]; ?>");
$connect = mysql_connect (...)
mysql_select_db ("mydb);
$ID = $_POST['ID'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sql = ("INSERT INTO contacts (fname, lname) VALUES ('$_POST[fname]', '$_POST[lname]')");
mysql_query($sql,$con) or die ("Error: ".mysql_error());
exit;
}
?>

I believe mysql_insert_id is the function you're looking for. It'll return the AUTO_INCREMENT ID of the field that was just inserted. You can then plug that into your header redirect. Just make sure to do the header redirect AFTER you insert the contact. It'll work just fine.
Code that should work:
<?php
if (isset($_POST['$fname'])) {
$connect = mysql_connect (...)
mysql_select_db ("mydb");
$ID = $_POST['ID'];
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$sql = "INSERT INTO contacts (fname, lname) VALUES ('$fname', '$lname')";
mysql_query($sql,$connection) or die ("Error: ".mysql_error());
header("location: http://www.mydomain.com/contacts/edit/?ID=".mysql_insert_id($connection));
exit;
}
?>
The code you posted was also susceptible to MySQL injections, so I mysql_real_escape_string'd your input to prevent that from happening. Always sanitize input before putting it into your query. I encourage you to look at the MySQLi functions that PHP has to offer.

You need to send the headers after the current script has done all that you want it to do. Sending headers doesn't necessarily immediately cancel the execution of that script; it can still persist for a bit, but you should do after you do your SQL calls.

The header doesn't terminate the run of the script.
If you use location redirect is a good practice to exit from the script, what you did correct.
Be aware one thing, do not put any output to the stdout before the header.

You can't embed php code in the header function (the <? echo $row['ID]; ?>). To achieve what you are trying to do, you should have the INSERT code before the header function. Then you should retrieve the ID of the contact you just entered and then call the header function, like so (assuming $id is the retrieved ID):
header("location: http://www.mydomain.com/contacts/edit/?ID=".$id);
To retrieve the ID of the last inserted row, you can use the mysql_insert_id function (reference), though it is recommended you use the mysqli version.

Related

multiple mysqli delete codes on one PHP page

I am still learing PHP and MySQLI and was wondering if it is possible to host multiple MySQLI delete queries on a single php page and have the url act on the corresponding query without confusion. I have this code here, I have search the web for an answer for 3 days but nothing I found seemed to be what I was looking for. Any help or properly described examples based on my code would be greatly appreciated.
my Code is:
<?php
session_start();
include ('dbconnect.php');
$userr = $_SESSION['usr_id'];
$uid=$_GET['pid'];
$pid=$_GET['phid'];
$user_id=$_GET['user'];
$fileID=$_GET['file'];
if($userr==$uid && $pid==$fileID){
echo "ERROR No. 9B2AP";
}else{
mysqli_query($con,"delete from images where userID='$uid' AND PhotoID='$pid'") or die (mysqli_error());
header ("location: /viewImage.php?pid=$uid");
}
if($userr==$user_id && $fileID==$pid){
echo "ERROR No. 39V41";
}else{
mysqli_query($con,"delete from music where userID='$user_id' AND Record_ID='$fileID'") or die (mysqli_error());
header ("location: /users/music-gallery/$user_id");
}
?>
No matter how many times I rewrite this code, when i delete an image or song using the code on this page, It redirects me only to the /users/music-gallery/ instead of the proper associated page. How might I get this fixed? Like I said, I am fairy new to PHP and MySQLI and any suggestions I believe should be described in details so I might be able to understand and comprehend how I made the mistake and I to fix and prevent it from happening again in later code. Please and Thank-you.
-M.S
For security reasons don't do this:
// Consider escaping the incoming data for better security
$uid=$_GET['pid'];
$pid=$_GET['phid'];
// ...
Since you are using MySQLi you can use this to escape your data:
$uid = mysqli_real_escape_string($con, $_GET['pid']);
You can use FILTERS to check input data type:
// If you are expecting an `INT` from $_GET['pid']
if (filter_var($_GET['pid'], FILTER_VALIDATE_INT))
{
echo 'pid is an int';
}
else
{
echo 'pid is not an int';
}
more on filters here.
The best of all, use prepared mysqli statements with stmt:
// prepare the statement
$stmt = $con->prepare("delete from images where userID=? AND PhotoID=?");
// bind variables to the '?' and set types --> `i` = integer
$stmt->bind_param("ii", $_GET['pid'], $_GET['phid']);
// execute query
$stmt->execute();
// Do the same for the next query
more on prepared statements here.
To solve your problem:
To exit a program right after a header you need to use exit(); after each header like this:
header ("location: /viewImage.php?pid=$uid");
exit();
For instance:
header ("location: /viewImage.php?pid=$uid");
// this line of code gets exucuted
// this too
// ...
header ("location: /viewImage.php?pid=$uid");
exit();
// Nothing gets executed as program terminates and redirects

Header did not work

Am having problem with header no returning to the page specified.The update work well, but instead of returning to profile.php, the up.php file will display blank page. up.php is the name of the file displayed below. please help me, have checked for the white space, i can not fix it
<?php
include('../_includes/configg.php');
session_start();
$id=$_SESSION['uid'];
?>
<?php
$phone= $_POST['phone'];
$phone2= $_POST['phone2'];
$address = $_POST['address'];
$fname= $_POST['fname'];
$sname = $_POST['sname'];
// turn autocommit off
mysqli_autocommit($link, FALSE);
// Insert data into mysql
$sql = "update trader set address='$address', phone='$phone', phone2='$phone2', sname='$sname', fname='$fname' where id= '$id'";
$result = mysqli_query($link, $sql);
// if successfully insert data into database, displays message "Successful".
if($result){
// Am having problem here is not returning to profile.php.
header('Location:profile.php');
}
else {
echo "ERROR";
}
mysqli_commit($link);
mysqli_close($link);
?>
First of all, use PDO::Mysql instead of deprecated mysql uses. Also, your SQL queries are full of sql injections, always sanitize your user input.
Now, why doesn't your header work? Because header edits the headers send with the page. After the headers comes the data. At the moment your PHP page is processing data (you end your PHP code, leave some blank and than start the <?php code again, so data output has been generated.) Try leaving the ?> and <?php out of the code.
session_start();
$id=$_SESSION['uid'];
$phone= $_POST['phone'];
$phone2= $_POST['phone2'];
Also make sure your include('../_includes/configg.php'); doesn't contain any data that will be send to the user (so leave the ?> out of it so it won't compile as a page).

addslashes() no slashes when inserting to database

For some reason addslashes is NOT adding slashes when inserting data into database. I thought I was using this right, but clearly not... When I submit data that has single or double quotes, it is just sending the exact string right in. Any ideas on how to make this work?
The code
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$entry = addslashes($_POST['entry']);
$uri = $_SERVER['HTTP_REFERER'];
//send chat
$query = mysqli_query($con, "INSERT INTO chat (username, entry) VALUES
('".$username."', '".$entry."')");
if ($query) {
header('Location: '. $uri);
} else {
echo 'Chat entry failed for an unknown reason - Please go back and try again';
}
?>
addslashes() is for escaping the string. If you got code:
$lastname = "O'Bama";
$query = "SELECT name FROM users WHERE lastname='$lastname'";
The query will produce an error because Bama will be treated as SQL statement. To prevent this you can use addslashes() so
echo addslashes($lastname); // returns O\'Bama
Now you can execute your query without any errors because your database will see value as "O'Bama".
Using addslashes() when dealing with databases is very bad practice. Since you're using PHP's mysqli extension, you should escape your data with mysqli_real_escape_string(). The PHP manual page for addslashes() explains why.

Redirect to another page after PHP script

I want to redirect to a confirmation page after the person has registered, once they have entered the details they need it is sent to the database using the PHP script below which all works. Although when I try to add a redirect using header, it does not run the PHP script. Any ideas to what I am doing wrong?
PHP
if (isset($_POST['firstname'], $_POST['surname'], $_POST['email'], $_POST['username'], $_POST['password'], $_POST['interest'])){
$firstname = ($_POST['firstname']);
$surname = ($_POST['surname']);
$username = ($_POST['username']);
$password1 = ($_POST['password']);
$email = ($_POST['email']);
$interest = ($_POST['interest']);
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
}
You should use MySQLi or PDO with prepared statements as mysql_ functions have been deprecated. You should at least look into using something like mysql_real_escape_string as you may be open to sql injection attacks.
Otherwise, like others have said use:
header("Location: new_page.php");
exit();
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location: page.php');
Include at the beginning of the script:
<?php
ob_start();
?>
You can add header('Location:yourpage.php');
$result = mysql_query("INSERT INTO user (firstname,surname,username,password,email,interestarea,user_type) VALUES ('$firstname','$surname','$username','$password1','$email','$interest','normal')");
header('Location:yourpage.php');
exit();
You can add the #ob_start(); on top of the page.
This is an educated guess on what your problem might be:
You say the page is redirecting, but the php is not parsed. So... if the page just displays your php, it means is outside php reading directory... check that pls (see if it starts with localhost/your ip/domain, etc).

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Categories