This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 5 years ago.
I have a file called inser_product.php which is where I have the function to insert products into the database table.
The function to insert the products looks like this:
<?php
include 'db.php';
function insert_product(){
try{
global $conn;
//prepare sql and bind parametes
$statement = $conn->prepare("insert into products (product_name, product_price, product_description) value (:product_name, :product_price, :product_description)");
$statement ->bindParam(':product_name', $product_name);
$statement ->bindParam(':product_price', $product_price);
$statement ->bindParam(':product_description', $product_description);
// executing the statement
$product_name = $_POST['product_name'];
$product_price = $_POST['product_price'];
$product_description = $_POST['product_description'];
$statement->execute();
header('Location: index.php');
}
catch(PDOException $e){
echo $query . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
Then I used the post method for the button and call the insert_product function:
<?php
if(isset($_POST['submit-button'])){
insert_product();
}
?>
All the insertion works fine but,
How can I redirect the page to my index.php after all the data is inserted?
As you can see I used the code below but it does not work.
echo "<script>window.open('index.php','_self')<script>";
You can use header() of php. But make sure there must be not echo or print before it
<?php
if(isset($_POST['submit-button'])){
insert_product();
header('Location: index.php');
}
?>
try{
$query = "insert into products(product_name, product_price, product_description) values ('$product_name','$product_price','$product_description')";
$conn->exec($query);
header('Location: index.php');
}
For php use:
header('location: index.php');
For JavaScript use
window.location.href='index.php';
Related
I want to update the marks of a student in php.
All the values are fetching properly from the table.
But after changing the value it is not updating.
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])=="")
{
header("Location: index.php");
}
else
{
$stid=intval($_GET['stid']);
if(isset($_POST['submit']))
{
$rowid=$_POST['id'];
$ct=$_POST['ct'];
$wt=$_POST['wt'];
$pro=$_POST['pro'];
$ter=$_POST['ter'];
foreach($_POST['id'] as $count => $id)
{
$c=$ct[$count];
$iid=$rowid[$count];
for($i=0;$i<=$count;$i++)
{
$sql="update tblresult set ct=:c,wt=:w,pro=:p,ter=:t where id=:iid ";
$query = $dbh->prepare($sql);
$query->bindParam(':c',c,PDO::PARAM_STR);
$query->bindParam(':w',w,PDO::PARAM_STR);
$query->bindParam(':p',p,PDO::PARAM_STR);
$query->bindParam(':t',t,PDO::PARAM_STR);
$query->bindParam(':iid',$iid,PDO::PARAM_STR);
$query->execute();
$msg="Result info updated successfully";
}
}
}
}
?>
enter image description here
It looks like the values you're using for bindParam aren't correct.
$query->bindParam(':c',c,PDO::PARAM_STR); for example looks like it should be:
$query->bindParam(':c', $ct, PDO::PARAM_STR);
I would also look at being more consistent with your variable names and maybe the 'Result info updated successfully' message is possibly a little presumptuous.
Is there something wrong with the syntax of the statement? I've been messing around with inserting different variables into the code and it still wont update in phpmyadmin. Pretty new with this language so please bear with me.
Pretty sure the line giving me the issue is:
$pdoQuery ="UPDATE `Lab4` SET `ActiveUser`=".$Yes." WHERE UserName=".$Email."";
I just don't know what the issue is...
<?php
//connect to the database
session_start(); //this must be the very first line on the php page, to register this page to use session variables
$_SESSION['timeout'] = time();
//if this is a page that requires login always perform this session verification
//require_once "inc/sessionVerify.php";
require_once "dbconnect.php";
require_once "inc/util2.php";
require_once "mail/mail.class.php";
include "header.php";
// $EmailCode = $_GET["Code"];
if (isset($_SESSION['Code'])){
echo $_SESSION['Code'];
echo $_SESSION['Email'];
}
?>
<?php
if (isset($_POST['Submit'])){
try {
$pdoConnect = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
}
catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
//$NotAnActiveUserYet = "No";
// mysql query to insert data
$Email = $_SESSION['Email'];
$Yes = "Yes";
$pdoQuery ="UPDATE `Lab4` SET `ActiveUser`=".$Yes." WHERE UserName=".$Email."";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute();
if ($pdoResult) {
echo 'Data Inserted';
} else {
echo 'Data Not Inserted';
}
}
?>
_Try something along these lines:
$params = array(
'ActiveUser' => $Yes,
'UserName' => $Email,
);
$pdoQuery ='UPDATE `Lab4` SET `ActiveUser`=:ActiveUser WHERE `UserName`=:UserName';
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->execute($params);
And as tadman said,... NEVER trust anything from a browser. (includes $_REQUEST, $_GET, $_POST, $_COOKIE, etc.)
i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?php
if(isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>
You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.
The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!
I am saving code in MySQL using php pdo, but the code is not working. my code is...
<?php
session_start();
include 'connection.php';
$question=$_POST['question'];
$answer=$_POST['desc'];
$query = $conn->prepare("insert into qa(ISSUE,DESC)values(':issue','desc')");
$query->bindParam(':issue',$question, PDO::PARAM_STR);
$query->bindParam(':desc', $answer, PDO::PARAM_STR);
$query->execute();
if(!$query)
{
$_SESSION['error']='Error in Posting Issue';
header('location:index.php');
}
but it will not insert the code in MySQL and also it it the data in MySQL like..
:issue!
desc
but whe I use this query...
<?php
session_start();
include 'connection.php';
$question=$_POST['question'];
$answer=$_POST['desc'];
$conn->exec("INSERT INTO qa (ISSUE,DESC) VALUES ('".$question."','".$answer."')");
if($conn)
{
$_SESSION['sucess']='Issue Posted Successfully';
header('location:index.php');
}
else
{
$_SESSION['error']='Error in Posting Issue';
header('location:index.php');
}
?>
else
{
$_SESSION['sucess']='Issue Posted Successfully';
header('location:index.php');
}
?>
Then it will only insert plane text, if I write then it will not insert anything into database, but the success session call.
What I want: I want that if I enter any type of data either php code or html or css, it will save to data base.
Any help will be highly appreciated...
Try this code as #u_mulder said..
<?php
session_start();
include 'connection.php';
$question=$_POST['question'];
$answer=$_POST['desc'];
$query = $conn->prepare("insert into qa(ISSUE, DESC) values (:issue, :desc)");
$query->bindParam(':issue', $question, PDO::PARAM_STR);
$query->bindParam(':desc', $answer, PDO::PARAM_STR);
$query->execute();
if(!$query)
{
$_SESSION['error']='Error in Posting Issue';
header('location:index.php');
}
it will solve the issue..
I have a table with inline editing using X-editable and everything is working fine including the value being submitted to the database, but for some reason it will display my echo in the else section.
Here is my PHP code:
require("config.php");
$userid = $_SESSION['user']['id'];
$sql = "SELECT fb_url, tw_url, ggl_url FROM social_preferences WHERE user_id = :userID";
$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
if(!empty($value)) {
try // save user selection to the database
{
$stmt = $db->prepare("UPDATE social_preferences SET tw_url = :twurl WHERE user_id = :userID");
$stmt->bindParam(":userID", $pk, PDO::PARAM_INT);
$stmt->bindParam(':twurl', $value);
$stmt->execute();
header("Location: admin-social.php");
die("Redirecting to admin-social.php");
} catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
}else {
echo 'Something went wrong!';
var_dump($value);
}
Here is my HTML code:
<a name="tw-url" id="tw-url" data-type="text" data-pk="<?php echo ($userid);?>" title="Edit"><?php echo ($result['tw_url']);?></a>
Like I said above everything seems to be working but it redirects to a page that will display my echo Something went wrong!even though it submitted the value to the DB. I included the var_dump to see if there is a value and that returns NULL. Can someone please help me? Any ideas why it would submit the right value to the database but redirect to my error?
Also, at what point does it send it to the database? I have a table in a form with a save button, but when I open the editable text and submit the new value does it send to the database when I save from the pop-over or when I click the save button in my table form?
The else statement is executing because when your details inserted into DB, you have set a header which redirects to the same page, in that case the variable $value value set to empty and your else statement executes.
The above answer is only valid if you set your header to same page.