set session value after insert query - php

I am trying to set a session variable after first successful insert query. I have a javascript Confirm to check if the user wants to add more data. If user wants to add more Products then I don't have to insert into the first table so keep the session value. If not then clear out the session data. I am not sure this is is right way of doing it. Could you please let me know if there are any suggestions.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
session_start();
if (empty($_SESSION['new_id']))
{
$first = $_POST["first"];
$first = mysql_real_escape_string($first);
$last = $_POST["last"];
$last = mysql_real_escape_string($last);
$insertsql = "INSERT INTO Table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = MySql_Insert_Id();
$_SESSION['new_id'] = $new_id;
}
$prodName = $_POST["prodName"];
$prodName = mysql_real_escape_string($prodName);
$prod_details = $_POST["prod_details"];
$prod_details = mysql_real_escape_string($prod_details);
$insertSQl2 = "INSERT INTO Table2($_SESSION['new_id'], Product_Name, Product_Details) VALUES ('".$new_id."', '" .$prodName. "', '" .$prod_details. "')";
$Result2 = mysql_query($insertSQl2) or die(mysql_error());
}
?>
<form>
//controls here
</form>
<?php
if($Result2 == true)
{
echo "Data saved Successfully";
echo '<script type="text/javascript">' , 'if confirm("Would like to add more Products?") ' , '</script>';
}
?>

Related

Update successfully but couldn't update into DB

I couldn't find any error. I tried the query on phpmyadmin and it works well but when I do in php page, it couldn't update into DB. The following code below:
$registerID = ($_POST['registerID']);
$firstName = ucwords(htmlspecialchars($_POST['firstName']));
$lastName = ucwords(htmlspecialchars($_POST['lastName']));
$emailAddress = htmlspecialchars($_POST['emailAddress']);
$mainAddress = ucwords(htmlspecialchars($_POST['fullAddress']));
$updateCity = ucwords($_POST['userCity']);
$updateCountry = $_POST['userCountry'];
$postalCode = strtoupper(htmlspecialchars($_POST['userZip']));
$profilePic = $_POST['pic'];
$updateProf = " UPDATE register_user
SET firstName='$firstName',
lastName='$lastName',
emailAddress='$emailAddress',
mainAddress='$mainAddress',
registerCity='$updateCity',
registerCountry='$updateCountry',
postalCode='$postalCode'
WHERE registerID = '$registerID'";
if (mysqli_query($mysqli, $updateProf)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
In the end, there are no errors after I updated on the webpage, it just show Record updated successfully. But it didn't update into DB. Any ideas?
UPDATED CODING
$checkProfile = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$editProfile = mysqli_query($mysqli,$checkProfile);
if ($editProfile) {
if (mysqli_num_rows($editProfile) > 0) {
header("Location: event?error=That name of email has already been taken");
} else {
$updateQuery = "UPDATE register_user
SET firstName = '$firstName',
lastName = '$lastName',
emailAddress = '$emailAddress',
mainAddress = '$mainAddress',
registerCity = '$updateCity',
registerCountry = '$updateCountry',
postalCode = '$postalCode'
WHERE registerID = '$registerID'";
$updateResult = mysqli_query($mysqli,$updateQuery);
header("Location: profileUser");
}
}
After I updated, it still doesn't work after I am using prepared statement. Any ideas?
Try executing the query first, saving it into a variable.
then, check if the query executed by doing:
if(!$query) echo "Query error : " . $mysqli->error;
This will give you more detailed error report.

cant save data into mysql (page become blank after press save button)

here is my code.....
after i press the save button cant save my data into mysql
and that page became blank
<?php $nama_pengguna =$_GET['nama_pengguna']; ?>
<?php include('../Connections/connection_db.php'); ?>
<?php
$Nama = $_POST['Nama'];
$No_KP = $_POST['No_KP'];
$NoNDP = $_POST['NoNDP'];
$Semester = $_POST['Semester'];
$kursus = $_POST['kursus'];
$NoTelPelajar = $_POST['NoTelPelajar'];
$alamat_1 = $_POST['alamat_1'];
$alamat_2 = $_POST['alamat_2'];
$Poskod = $_POST['Poskod'];
$Bandar = $_POST['Bandar'];
$Negeri = $_POST['Negeri'];
$namabp = $_POST['namabp'];
$No_Tel_bp = $_POST['No_Tel_bp'];
$alamat_1_bp = $_POST['alamat_1_bp'];
$alamat_2_bp = $_POST['alamat_2_bp'];
$poskod_bp = $_POST['poskod_bp'];
$Bandar_bp = $_POST['Bandar_bp'];
$Negeri_bp = $_POST['Negeri_bp'];
$data =mysql_query ("INSERT INTO maklumat_pelajar (No_KP, Nama, No.NDP, Semester, Kursus, No_Tel_Pelajar, Alamat, Alamat_2, Poskod, Bandar, Negeri, Nama_BP, No_Tel_BP, Alamat_BP, Alamat_BP_2, Poskod_BP, Bandar_BP, Negeri_BP) VALUES ('".$_POST['No_KP']. "','".$_POST['Nama']. "','".$_POST['NoNDP']. "','".$_POST['Semester']. "','".$_POST['kursus']. "','".$_POST['NoTelPelajar']. "','".$_POST['alamat_1']. "','".$_POST['alamat_2']. "','".$_POST['Poskod']. "','".$_POST['Bandar']. "','".$_POST['Negeri']. "','".$_POST['namabp']. "','".$_POST['No_Tel_bp']. "','".$_POST['alamat_1_bp']. "','".$_POST['alamat_2_bp']. "','".$_POST['poskod_bp']. "','".$_POST['Bandar_bp']. "','".$_POST['Negeri_bp']. "')");
//$data = mysql_query($query);
echo $data;
//header ("location:../bppl/register_pelajar.php?nama_pengguna=$nama_pengguna");
?>
can anyone got another way to do it?
change that
No.NDP
to
`No.NDP`
in your columns
you should escape your variables first before inserting them by
mysql_real_escape_string()
to see what error you have use mysql_error() like that
$data =mysql_query ("INSERT INTO ...........")or die (mysql_error());
Try this.
$sql=mysql_query("INSERT INTO maklumat_pelajar('$No_KP','$nama','$NoNDP',
'$smester','$kursus',
'$NoTelPelajar','$alamat_1','$alamat_2','$Poskod','$Bandar','$Negeri',
'$namabp','$No_Tel_bp','$alamat_1_bp','$alamat_2_bp','$poskod_bp',
'$Bandar_bp','$Negeri_bp')");
if(!$sql) {
die("Database query failed: " . mysql_error());
}

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

storing username from session to database while form submission using php

I have a simple question,
I have a login and workspace area.
After the user logs in It shows the username of the logged in user at workplace as what I wanted. Now my problem is when user finish filling form available in his workspace the form is then stored in database also i need the username that is coming from session also get stored to the database.
here is code that is storing username and maintaining session after user reach at workspace after login:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/MainProject/connect/auth.php');
session_start();
?>
The final version of the updated insert file :
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
// session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>
In the logging in process, you must store your username in a session
$_SESSION['username'] = $username;
in the process of saving the form, you can call session_start(); and get the session using
$tobeinserted = $_SESSION['username'];
I believe
Remove comment in session start.
Use this.
//This code is included to check session and store username
<?php
require_once('..\connect\auth.php');
session_start();
$usern = $_SESSION['SESS_FIRST_NAME'];
?>
<?php
mysql_connect('localhost','root','');
mysql_select_db('main_project') or die (mysql_error());
if(isset($_POST['WID'])){
for ($ix=0; $ix<count($_POST['WID']); $ix++)
{
$WID = mysql_real_escape_string(#$_POST['WID'][$ix]);
$website = mysql_real_escape_string(#$_POST['website'][$ix]);
//var_dump("<pre>", $_POST['cat']); die(); // Debugger for checking cat counter.
// $cat = implode(",", mysql_real_escape_string($_POST['cat'][$ix]));
if(is_array(#$_POST['cat'][$ix]))
$cat = mysql_real_escape_string(implode(',', #$_POST['cat'][$ix]));
else
$cat = mysql_real_escape_string(#$_POST['cat'][$ix]);
$email = mysql_real_escape_string(#$_POST['email'][$ix]);
$cform = mysql_real_escape_string(#$_POST['cform'][$ix]);
$contactp = mysql_real_escape_string(#$_POST['contactp'][$ix]);
$contacts = mysql_real_escape_string(#$_POST['contacts'][$ix]);
$fax = mysql_real_escape_string(#$_POST['fax'][$ix]);
$Ctype = mysql_real_escape_string(#$_POST['Ctype'][$ix]);
//$usern = mysql_real_escape_string(#$_POST['usern'][$ix]);
$sql_res = mysql_query("INSERT INTO website_01data (WID,website,cat,email,cform,contactp,contacts,fax,Ctype,TimeStamp,usern)
VALUES ('".$WID."', '".$website."', '".$cat."', '".$email."','".$cform."', '".$contactp."', '".$contacts."', '".$fax."', '".$Ctype."', Now(), '".$usern."' )");
$sql_res = mysql_error();
}//end for..
echo "<p><span style=\"color: red;\">Thank You; your records are sent to database. DO NOT REFRESH THE PAGE or data will be sent again.</span></p>";
}
?>

passing and receiving string variables using php

I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']

Categories