Activate headers after php request is complete - php

I am currently working on a site where users can upload images up to 10mb. When the users press upload, the file is stored in a directory on the server, and then the page is redirected through the use of a header. Note that I also put ob start() at the beginning of the script. The problem I'm having is that the header redirect activates before the request is complete, so users get logged out, or an internal server error occurs. Same thing happens when you delete the large file. I've tried removing the redirect and its fine, so i'm sure that's the problem. Is there a way to get the header redirect only after the php request (image upload) is complete?
Thanks!
Edit: Code sample
if (empty($errors)) {
// Get the filename minus the file extension:
$filename = substr($image["name"], 0, strrpos($image["name"], "."));
// Append the appropriate extension
$filename .= $validMimes[$image['type']];
$location = "/home/shoplft/users/$user_id/$foldername/$filename";
move_uploaded_file($tmp_name, $location);
if($secondcategory=="0") {
mysql_query("INSERT INTO products (users_user_id, name, brand, city, country, store, website, price, keywords, productlocation, filename) VALUES ('$user_id', '$productname', '$productbrand', '$city', '$country', '$store', '$website', '$price', '$tagwords', '$location', '$filename')") or die('Invalid query: ' . mysql_error());
$pic_id = mysql_insert_id();
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$firstcategory')");
if(!empty($price)) {
mysql_query("INSERT INTO svalues (products_products_id, products_users_user_id, svalue) VALUES ('$pic_id', '$user_id', '$price') ");
}
}
else {
mysql_query("INSERT INTO products (users_user_id, name, brand, city, country, store, website, price, keywords, productlocation, filename) VALUES ('$user_id', '$productname', '$productbrand', '$city', '$country', '$store', '$website', '$price', '$tagwords', '$location', '$filename')") or die('Invalid query: ' . mysql_error());
$pic_id = mysql_insert_id();
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$firstcategory')");
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$secondcategory')");
if(!empty($price)) {
mysql_query("INSERT INTO svalues (products_products_id, products_users_user_id, svalue) VALUES ('$pic_id', '$user_id', '$price') ");
}
}
header("Location: product.php?id=$pic_id");//prolly should separate data processing from output
}

Try this
if (empty($errors)) {
// Get the filename minus the file extension:
$filename = substr($image["name"], 0, strrpos($image["name"], "."));
// Append the appropriate extension
$filename .= $validMimes[$image['type']];
$location = "/home/shoplft/users/$user_id/$foldername/$filename";
if(!#copy($tmp_name, $location))
{
$errors[] = 'Error';
}
if (empty($errors))
{
if($secondcategory=="0") {
mysql_query("INSERT INTO products (users_user_id, name, brand, city, country, store, website, price, keywords, productlocation, filename) VALUES ('$user_id', '$productname', '$productbrand', '$city', '$country', '$store', '$website', '$price', '$tagwords', '$location', '$filename')") or die('Invalid query: ' . mysql_error());
$pic_id = mysql_insert_id();
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$firstcategory')");
if(!empty($price)) {
mysql_query("INSERT INTO svalues (products_products_id, products_users_user_id, svalue) VALUES ('$pic_id', '$user_id', '$price') ");
}
}
else {
mysql_query("INSERT INTO products (users_user_id, name, brand, city, country, store, website, price, keywords, productlocation, filename) VALUES ('$user_id', '$productname', '$productbrand', '$city', '$country', '$store', '$website', '$price', '$tagwords', '$location', '$filename')") or die('Invalid query: ' . mysql_error());
$pic_id = mysql_insert_id();
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$firstcategory')");
mysql_query("INSERT INTO categories (products_products_id, products_users_user_id, category) VALUES('$pic_id', '$user_id', '$secondcategory')");
if(!empty($price)) {
mysql_query("INSERT INTO svalues (products_products_id, products_users_user_id, svalue) VALUES ('$pic_id', '$user_id', '$price') ");
}
}
header("Location: product.php?id=$pic_id");//prolly should separate data processing from output
}
}

Related

PHP MySQL Insert not working without error

i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?
i checked also my database and table values and my html names
<?php
if(isset( $_POST['submit'] ) )
{
$name = $_POST['p_name'];
$price = $_POST['p_price'];
$type = $_POST['p_type'];
$des = $_POST['p_desc'];
$img = 'images/is7.jpeg';
//***********************
require_once 'setting.php';
$dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_set_charset($dbc, 'utf8');
$query = "INSERT INTO products(name, price, type, des, img)
VALUES('$name', '$price', '$type', $des, '$img')";
mysqli_query($dbc, $query);
mysqli_close($dbc);
header('Location: success.php');
exit;
}
?>
Did you try to put single quotes around description variable?
Change
VALUES('$name', '$price', '$type', $des, '$img')";
To
VALUES('$name', '$price', '$type', '$des', '$img')";
Cheers
"INSERT INTO products(name, price, type, des, img) VALUES('$name', '$price', '$type', '$des', '$img')";
OR
"INSERT INTO products(name, price, type, des, img) VALUES(?, ?, ?, ?, ?)";
Replare this formate
<?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('$name', '$price', '$type', $des, '$img')";
?>
TO
<?php
$query = "INSERT INTO products(name, price, type, des, img)VALUES('".$name."', '".$price."', '".$type."', '".$des."', '".$img."')";
?>
In feature apply mySQL error check up to get mySQL error.

How to use php variables as table name to insert records in mysql

$id = $_SESSION['id'];
i have the table name stored in the $id variable.
when i use the variable name with sql query it doesn't work
$sql = "INSERT INTO karthick.$id (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
when i replace the karthick.$id as karthick.ford it works fine. but i want to use the variable stored in $id as my table name. how do i do it.
Edit---------------------------
my php code
<?php
session_start();
$id = $_SESSION['id'];
require 'database.php';
/*$sql = "CREATE TABLE karthick.details (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL)";
if($conn->query($sql)===TRUE){
echo "table created";
}else{
echo "table not created";
}*/
$name = mysqli_real_escape_string($conn, $_POST["cname"]);
$tin = mysqli_real_escape_string($conn, $_POST["tin"]);
$address = mysqli_real_escape_string($conn, $_POST["address"]);
$product = mysqli_real_escape_string($conn, $_POST["product"]);
$ddate = mysqli_real_escape_string($conn, $_POST["date"]);
$invoice = mysqli_real_escape_string($conn, $_POST["invoice"]);
$transport = mysqli_real_escape_string($conn, $_POST["transport"]);
$cutting = mysqli_real_escape_string($conn, $_POST["date"]);
$amount = mysqli_real_escape_string($conn, $_POST["amount"]);
$vat = mysqli_real_escape_string($conn, $_POST["vat"]);
$val = 'karthick'.$id;
echo $val;
$sql = "INSERT INTO $val (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
if($conn->query($sql)===TRUE){
echo "record inserted";
}else{
echo "not inserted".$conn->error;
}
$conn->close();
?>
Try this one.
$val = 'karthick'.$id;
$sql = "INSERT INTO $val (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
Try using "INSERT INTO karthick.".$id." (name, tin, address, product, invoice, transport
Place the $id in braces{} like karthick.{$id}. The query should be like below.
$sql = "INSERT INTO karthick.{$id} (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
$val = 'karthick'.$id;
$val = str_replace(" ","",$val);
$sql = "INSERT INTO $val (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('$name', '$tin', '$address', '$product', '$invoice', '$transport', '$cutting', '$amount', '$vat')";
Try
$sql = "INSERT INTO karthick.{$id} (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('{$name}', '{$tin}', '{$address}', '{$product}', '{$invoice}', '{$transport}', '{$cutting}', '{$amount}', '{$vat}')";
You are creating karthick.details table instead of karthick.session_id
First method :
Try putting the PHP variables inside curly braces {}
Like:
$sql = "INSERT INTO karthick.{$id} (name, tin, address, product, invoice, transport, cutting, amount, vat) VALUES ('{$name}', '{$tin}', '{$address}', '{$product}', '{$invoice}', '{$transport}', '{$cutting}', '{$amount}', '{$vat}')";
Second method :
Use PHP variables outside quotes
Like:
$sql = " INSERT INTO karthick.".$id." (name, tin, address .....
Update
try using `` to enclose your table like,
$val = "`karthick`.`".$id."`";

Error Column count doesn't match value count at row 1?

where is error.....
Column count doesn't match value count at row 1
mysqli_select_db($conn, $data);
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat', "
. "'$sn', '$art', '$img', "
. "'$y', '$g', "
. "'$sl', '$time', '', '0')";
$success = mysqli_query($conn, $save) or die(mysqli_error($conn));
$page = "index.php";
$this->pageRedirect($page);
where is error.....
Column count doesn't match value count at row 1
remove '' from your query to be:
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat','$sn', '$art', '$img', '$y', '$g', '$sl', '$time', '', '0')";
Try this:
$save = "INSERT INTO SONG_AS(`ALBUM`, `CATEGORY`, `SUB_CATEGORY`,
`SONG_NAME`, `ARTIST`, `ART_LINK`,
`YEAR`, `GENRE`, `SONG_LINK`, `POST_ON`,
`POST_BY`, `TOTAL_DOWNLOAD`)
VALUES('".$albm."', '".$cat."', '".$scat."','".$sn."', '".$art."', '".$img."', '".$y."', '".$g."', '".$sl."', '".$time."', '', '0')";
$query = "INSERT INTO employee VALUES ($empno','$lname','$fname','$init','$gender','$bdate','$dept','$position','$pay','$dayswork','$otrate','$othrs','$allow','$advancesance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno','lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}

Getting the SAME random generated value in two different locations

So I have two different Order forms. If one is completed and then they check out it generates only one order...
But if they select to add more products it adds another one to the form..
For the first order number I want it to be a random generated number..
But for the SECOND order number at the bottom of the code. I need it to be the same number that was generated for the first order.
How Can I do that?
if($row == 1) {
$sqll = mysqli_query($con, "UPDATE BubbleGum SET pendingOrders=pendingOrders + 1 WHERE Name='".$name."'");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', 'THIS NUMBER NEEDS TO BE RANDOM')");
} else {
$sql = mysqli_query($con, "INSERT INTO Bubblegum (BrainID, name, street, city, state, zip, height, weight) VALUES ('', '$name', '$street', '$city', '$state', '$zip', '$height', '$weight')");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', '')");
}
if(isset($_SESSION['more'])) {
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type2', '$amount2', '$equipment2', 'THIS NUMBER NEEDS TO BE THE SAME RANDOM NUMBER AS ABOVE')");
}
}
update:
If I do what has been suggested. Then it only adds one entry into my mysql database... It does NOT add the entry at the bottom.
$random = rand (1 , 10);
while($roww = mysqli_fetch_array($query)) {
//count rows, If exist, then username exist
$row = mysqli_num_rows($query);
$brain = $roww['BrainID'];
if($row == 1) {
$sqll = mysqli_query($con, "UPDATE BubbleGum SET pendingOrders=pendingOrders + 1 WHERE Name='".$name."'");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', '$random')");
} else {
$sql = mysqli_query($con, "INSERT INTO BubbleGum (BrainID, name, street, city, state, zip, height, weight) VALUES ('', '$name', '$street', '$city', '$state', '$zip', '$height', '$weight')");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', '$random')");
}
if(isset($_SESSION['more'])) {
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type2', '$amount2', '$equipment2', '$random')");
}
}
As mentioned in the comments, just generate the number outside the scope of the if statements, eg:
$random = rand (1 , 10);
if($row == 1) {
$sqll = mysqli_query($con, "UPDATE BubbleGum SET pendingOrders=pendingOrders + 1 WHERE Name='".$name."'");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', $random)");
} else {
$sql = mysqli_query($con, "INSERT INTO Bubblegum (BrainID, name, street, city, state, zip, height, weight) VALUES ('', '$name', '$street', '$city', '$state', '$zip', '$height', '$weight')");
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type', '$amount', '$equipment', '')");
}
if(isset($_SESSION['more'])) {
$sqli = mysqli_query($conn, "INSERT INTO Pending (BrainID, name, Type, amount, equipment, orderNumber) VALUES ('$brain', '$name', '$type2', '$amount2', '$equipment2', $random)");
}
}

How to insert multiple image names in a same row and display it php-mysql

I am struggling on MySQL help me.
I am using
$sql = "INSERT INTO properties (agent_id, property_name, category, location, property_type, search_radius, price, bed_rooms, bath_rooms, commercial_type, area, address, description, image_name, date_added)
VALUES ('$agent_id', '$property_name', '$listing_for', '$city', '$property_type', '$area', '$price', '$beds', '$baths', '$commercial_type', '$area_sf', '$address', '$description', '".$filename."', now() )" ;
This query to insert my values into database. But here image_name ($filename) contains 3 images. I am getting this names by using array and insert into DB. Here all the fields are single. But image_name contains 3 values. When i use this script inside for loop, then totally 3 rows are inserted. When I use outside for loop it will be inserted last $filename. So my need is I want to add all 3 image_names and other data into a single row. After that I need to fetch all the data display it. How can I do that. Help me mates. Thanks.
Use this code,
foreach ($filename as $key => $value) {
$array[] = $value;
}
$arrayvalue = json_encode($array);
$sql = "INSERT INTO properties (agent_id, property_name, category, location, property_type, search_radius, price, bed_rooms, bath_rooms, commercial_type, area, address, description, image_name, date_added)
VALUES ('$agent_id', '$property_name', '$listing_for', '$city', '$property_type', '$area', '$price', '$beds', '$baths', '$commercial_type', '$area_sf', '$address', '$description', '".$arrayvalue."', now() )" ;
You can use something like:
implode("|",$filename)
and in SQL query like
$sql = "INSERT INTO properties (agent_id, property_name, category, location, property_type, search_radius, price, bed_rooms, bath_rooms, commercial_type, area, address, description, image_name, date_added)
VALUES ('$agent_id', '$property_name', '$listing_for', '$city', '$property_type', '$area', '$price', '$beds', '$baths', '$commercial_type', '$area_sf', '$address', '$description', '". implode("|",$filename) ."', now() )";
And similarly use
explode("|",$filename)
when you retrieve the data
Use below code to insert images.
$images_array = array("img1.jpg","img2.jpg","img3.jpg");
$filename = implode( ",", $images_array );
and in SQL query like
$sql = "INSERT INTO properties (agent_id, property_name, category, location, property_type, search_radius, price, bed_rooms, bath_rooms, commercial_type, area, address, description, image_name, date_added)
VALUES ('$agent_id', '$property_name', '$listing_for', '$city', '$property_type', '$area', '$price', '$beds', '$baths', '$commercial_type', '$area_sf', '$address', '$description', '".$filename."', now() )" ;
and when retrieving data use this to get array of images back
$images_array = explode( ",", $data['image_name'] );

Categories