Hey guys for some reason the code is not working its not echo the success which is weird it inserts the mysql info but just not echo the success if you guy's know the problem please post a fix or something thanks a lot guy's!
<?php
//Initiliaze Database connection
require("config.php");
//IMPORTANT STUFF
$username = mysql_real_escape_string(stripslashes($_POST["strUsername"]));
$password = mysql_real_escape_string(stripslashes($_POST["strPassword"]));
$pass1 = gen_token($password, $username);
$age = mysql_real_escape_string(stripslashes($_POST["intAge"]));
$dob = mysql_real_escape_string(stripslashes($_POST["strDOB"]));
$email = mysql_real_escape_string(stripslashes($_POST["strEmail"]));
$gender = mysql_real_escape_string(stripslashes($_POST["strGender"]));
$classid = mysql_real_escape_string(stripslashes($_POST["ClassID"]));
$eyecolor = mysql_real_escape_string(stripslashes($_POST["intColorEye"]));
$skincolor = mysql_real_escape_string(stripslashes($_POST["intColorSkin"]));
$haircolor = mysql_real_escape_string(stripslashes($_POST["intColorHair"]));
$hairid = $_POST['HairID'];
//Checks if Email has Already been used
$emailcheck = mysql_query("SELECT id FROM users WHERE Email='$email'") or die("status=Error&strReason=" . mysql_error());
if (mysql_num_rows($emailcheck) != 0) {
die("status=Taken&strReason=The email is already in used by another user.");
}
//Checks If Username has been Taken
$sql = mysql_query("SELECT * FROM users WHERE Username = '$username'") or die("status=Error&strReason=" . mysql_error());
if (mysql_num_rows($sql) !=0) {
die("status=Taken&strReason=The username is already in use by another character.");
} else {
//Sets Hairname & hairfile
switch ($hairid) {
//MALE HAIR
case 52:
$hairname = 'Default';
$hairfile = 'hair/M/Default.swf';
break;
case 55:
$hairname = 'Goku1';
$hairfile = 'hair/M/Goku1.swf';
break;
case 58:
$hairname = 'Goku2';
$hairfile = 'hair/M/Goku2.swf';
break;
case 64:
$hairname = 'Normal2';
$hairfile = 'hair/M/Normal2.swf';
break;
case 92:
$hairname = 'Ponytail8';
$hairfile = 'hair/M/Ponytail8.swf';
break;
//FEMALE HAIR
case 14:
$hairname = 'Pig1Bangs1';
$hairfile = 'hair/F/Pig1Bangs1.swf';
break;
case 18:
$hairname = 'Pig2Bangs2';
$hairfile = 'hair/F/Pig2Bangs2.swf';
break;
case 26:
$hairname = 'Pony2Bangs2';
$hairfile = 'hair/F/Pony2Bangs2.swf';
break;
case 83:
$hairname = 'Bangs2Long';
$hairfile = 'hair/F/Bangs2Long.swf';
break;
case 84:
$hairname = 'Bangs3Long';
$hairfile = 'hair/F/Bangs3Long.swf';
break;
}
$time = date("Y-m-d");
//Inserts Character Info into DB
$sql2 = mysql_query("INSERT INTO `users` (`Username`, `Password`, `Access`, `ActivationFlag`, `Age`, `Gender`, `Email`, `Level`, `Gold`, `Coins`, `Exp`, `ColorHair`, `ColorSkin`, `ColorEye`, `ColorBase`, `ColorTrim`, `ColorAccessory`, `DateCreated`, `UpgradeExpire`, `UpgradeDays`, `BankSlots`, `HouseSlots`, `BagSlots`, `HairID`, `HairFile`, `HairName`, `Permamute`, `Quests`, `Settings`, `Achievement`, `Country`, `AchievementID`, `CurrentServer`) VALUES ('$username', '$pass1', '0', '5', '15', '$gender', '$email', '1', '0', '0', '0', '$haircolor', '$skincolor', '$eyecolor', '0', '0', '0', '$time', '$time', '-1', '0', '20', '150', '$hairid', '$hairfile', '$hairname', '0', '00000000000000000000000000000000000000000000000000', '0', '0', 'US', '', 'Offline');") or die("status=Error&strReason=" . mysql_error());
//Selects New User ID
$sql3 = mysql_query("SELECT * FROM users WHERE Username='$username'") or die("status=Error&strReason=" . mysql_error());
$user = mysql_fetch_assoc($sql3) or die("status=Error&strReason=" . mysql_error());
$userId = $user['id'];
//Add's Starting Armor
switch ($classid) {
case 2:
$addarmour = mysql_query("INSERT INTO users_items (itemid, userid, equipped, equipment, level) VALUES ('2', '$userId', '1', 'ar', '1')");
break;
case 4:
$addarmour = mysql_query("INSERT INTO users_items (itemid, userid, equipped, equipment, level) VALUES ('4', '$userId', '1', 'ar', '1')");
break;
case 3:
$addarmour = mysql_query("INSERT INTO users_items (itemid, userid, equipped, equipment, level) VALUES ('3', '$userId', '1', 'ar', '1')");
break;
case 5:
$addarmour = mysql_query("INSERT INTO users_items (itemid, userid, equipped, equipment, level) VALUES ('5', '$userId', '1', 'ar', '1')");
break;
}
// ADDS DEFAULT WEAPON
$addweapon = mysql_query("INSERT INTO users_items (itemid, userid, equipped, equipment, level) VALUES ('1', '$userId', '1', 'Weapon', '1')" );
// ADDS USERS FRIEND LIST
$addfriends = mysql_query("INSERT INTO users_friends (userid, friends) VALUES ($userId, '')" );
//SUCCESS
echo "status=Success";
}
function gen_token($pass, $salt) {
$salt = strtolower($salt);
$str = hash("sha512", $pass.$salt);
$len = strlen($salt);
return strtoupper(substr($str, $len, 17));
}
?>
I count 4 INSERT commands that will ALWAYS occur (assuming successful). Is this correct, or are only some of them working?
Nothing jumps out as incorrect. You're storing the mysql_query result in variables, but not doing anything with them. Maybe try testing those values to see what's returned by MySQL?
You're also not testing to see if any of the POST'ed values are null, empty, or invalid. Always validate what's being POST'ed - for quick debugging, you could do a print_r($_POST);.
Related
I'm trying to insert values to another table using conditional statement but the values does not insert inside the table.
<?php
if($_POST['save'])
{
$pr_no = $_POST['pr_no'];
$s = mysqli_query($connect,"SELECT purchase_no FROM `sms_request` WHERE purchase_no = '".$pr_no."'");
if(mysqli_num_rows($s) > 0)
{
echo"<script type='text/javascript'>
alert('Purchase No. Existed!');
window.location.href = 'sms_supply management.php';
</script> ";
}
else
{
$fcluster = $_POST['fund_cluster'];
$osection = $_POST['office_section'];
$pr_no = $_POST['pr_no'];
$rcode = $_POST['responsibility_code'];
$desig = $_POST['desig'];
$requester = $_POST['requester'];
$loc = $_POST['loc'];
$purpose = $_POST['prpose'];
$ename = $_POST['entity_name'];
$date = $_POST['date'];
$dateA = date("Y-m-d",strtotime($date));
$radioo = $_POST['supply_type'];
$ins = mysqli_query($connect, "INSERT INTO sms_purchaserecord(purchase_no, supply_type) VALUES ('".$pr_no."', '".$radioo."')");
$insS = mysqli_query($connect, "INSERT INTO sms_ris(purchase_no, ris_num) VALUES ('".$pr_no."', '".$pr_no."')");
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
$inS = mysqli_query($connect, "INSERT INTO sms_iar(iar_num, purchase_no) VALUES ('".$pr_no."', '".$pr_no."')");
$select = mysqli_query($connect, "SELECT request_IDnum FROM sms_request WHERE purchase_no = '".$pr_no."'");
while ($row = mysqli_fetch_array($select)){
$rnum = $row['request_IDnum'];
}
$select2 = mysqli_query($connect, "SELECT * FROM sms_branchloc WHERE loc_ID_no = '".$loc."'");
while ($row1 = mysqli_fetch_array($select2)){
$loc_num = $row1['loc_ID_no'];
}
if ($rnum != NULL AND $loc_num != NULL){
$insert2 = mysqli_query($connect, "INSERT INTO sms_requester(request_IDnum, name, loc_ID_no, position) VALUES ('".$rnum."', '".$requester."', '".$loc_num."', '".$desig."')");
}
if ($radioo == 'expandable'){
$insertI = mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_num, description, unit, quantity, price) VALUES ('".$pr_num."','".$unit."','".$desc."','".$qty."','".$cost."')");
}
// If I choose expandable on the radio button it will insert into the inventory_status table
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}
echo"<script type='text/javascript'>
alert('Purchase Request Save.');
window.location.href = 'sms_supply management.php';
</script>";
}
}
What I wanted to do is if I choose expandable on the radio button it will insert the values into the inventory_status table. The block of code that didn't work is
if ($radioo == 'expandable')
{
$insertI = mysqli_query($connect, "INSERT INTO
inventory_status(stock_prop_num, description, unit, quantity, price) VALUES('".$pr_num."', '".$unit."','".$desc."', '".$qty."', '".$cost."')");
Do I need to connect the 2 tables with a primary key and foreign key?
I have a form which contain two table. Each of the table able to add table row. which mean when submit a form using isset $_POST by using "for" right? the things that i concern about is how to submit a single form which contain two table (both of them have function add table row) in single database table. Both of table contain slightly different attribute but in the same database table. i was searching this for a week and didnt found solution yet. I only able to submit a form which contain one table (which have add table row). How about if there is two table but insert into same database table?
if(isset($_POST['submitbtn'])){
//others
$merchant = $_POST['merchant'];
$remark = $_POST['remark'];
$docno = $_POST['docno'];
$category = $_POST['category'];
$claim_amount = $_POST['claim_amount'];
//airfare
$airline = $_POST["airline"];
$origin = $_POST["origin"];
$destination = $_POST["destination"];
$descript = $_POST["desc"];
$docno_air = $_POST["docno_air"];
$category_air = $_POST["category_air"];
$claim_amount_fare = $_POST["claim_amount_fare"];
$email = $ColUser['Email'];
$euser = $_SESSION['UserId'];
$reportName = $_POST['reportname'];
$start_date = date("Y-m-d");
$status="open";
$purpose = $_POST["purpose"];
//get approval
$getapproval = "SELECT * FROM `approve_by` WHERE `user_id` = '".$_SESSION['UserId']."'";
$approvalget = mysqli_query($mysqli,$getapproval);
$appid = mysqli_fetch_assoc($approvalget);
$app1 = $appid['approval_1'];
$app2 = $appid['approval_2'];
$app3 = $appid['approval_3'];
//generate travel id
$travelprefix= "SELECT * FROM `prefix` WHERE `description` = 'Travel'";
$result_travel = mysqli_query($mysqli, $travelprefix);
$travel_info = mysqli_fetch_assoc($result_travel);
$travel_pre = $travel_info['prefix'];
$travel_old_num = $travel_info['running_number'] + 1;
$travel_new = sprintf("%05d", $travel_old_num);
$travel_date_append = date('mY');
$travel_number = $travel_pre."-".$travel_date_append."-".$travel_new;
//generate report id
$reportprefix= "SELECT * FROM `prefix` WHERE `description` = 'REPORT'";
$result_report = mysqli_query($mysqli, $reportprefix);
$report_info = mysqli_fetch_assoc($result_report);
$report_pre = $report_info['prefix'];
$report_old_num = $report_info['running_number'] + 1;
$report_new = sprintf("%05d", $report_old_num);
$report_date_append = date('mY');
$report_number = $report_pre."-".$report_date_append."-".$report_new;
if (!empty($_POST['airline']))
{
for ($i = 0; $i < count($_POST["airline"]); $i++){
$airline = $_POST["airline"][$i];
$origin = $_POST["origin"][$i];
$destination = $_POST["destination"][$i];
$descript = $_POST["desc"][$i];
$docno_air = $_POST["docno_air"][$i];
$category_air = $_POST["category_air"][$i];
$claim_amount_fare = $_POST["claim_amount_fare"][$i];
//$upload_dir = 'upload';
//$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$targetPaths="upload/";
$filefare = $targetPaths.rand(1000,100000)."-".$_FILES['bill_image_air']['name'][$i];
$file_loc = $_FILES['bill_image_air']['tmp_name'][$i];
$file_basename = substr($filefare, 0, strripos($filefare, '.'));
//$flink='http://localhost/new_exp/'.$file;
move_uploaded_file($file_loc,$filefare);
$mrecordprefix= "SELECT * FROM `prefix` WHERE `description` = 'Category'";
$mresult_record = mysqli_query($mysqli, $mrecordprefix);
$mrecord_info = mysqli_fetch_assoc($mresult_record);
$mrecord_pre = $mrecord_info['prefix'];
$mrecord_old_num = $mrecord_info['running_number'] + 1;
$mrecord_new = sprintf("%05d", $mrecord_old_num);
$mrecord_date_append = date('mY');
$mrecord_number = $mrecord_pre."-".$mrecord_date_append."-".$mrecord_new;
$save_running_records = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Category'";
$save_running_report = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Report'";
$save_running_travel = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Travel'";
$save_new_record = "INSERT INTO `report`(`reportname`, `report_ref`, `UserId`, `CategoryId`, `travel_record`, `remark`, `claim_amount`, `bill_image`, `bill_image_type`, `docno`, `origin`, `airline`, `destination`, `email_from`, `approval_1`, `approval_2`, `approval_3`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$save_count = "INSERT INTO `categorycount`(`CategoryId`, `amount`, `userid`, `categoryno`) VALUES (?, ?, ?, ?)";
$stmt6 = $mysqli->prepare($save_running_records);
$stmt4 = $mysqli->prepare($save_running_report);
$stmt2 = $mysqli->prepare($save_running_travel);
$stmt5 = $mysqli->prepare($save_new_record);
$stmt7 = $mysqli->prepare($save_count);
$stmt6->bind_param('s', $mrecord_old_num);
$stmt4->bind_param('s', $report_old_num);
$stmt2->bind_param('s', $travel_old_num);
$stmt5->bind_param('ssiisssbssssssiii', $reportName, $report_number, $euser, $category_air, $travel_number, $descript, $claim_amount_fare, $filefare, $filefare, $docno_air, $origin, $airline, $destination, $email, $app1, $app2, $app3);
$stmt7->bind_param('isis', $category_air, $claim_amount_fare, $euser, $mrecord_number);
if ($stmt5->execute() == false){
echo 'Fifth query failed: ' . $mysqli->error;
} else {
if ($stmt2->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt4->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt7->execute() == false) {
echo 'gl B query failed: ' . $mysqli->error;
} else {
if($stmt6->execute() == false){
echo 'gl C query failed: ' . $mysqli->error;
}
$stmt6->close();
}
$stmt7->close();
}
$stmt4->close();
}
$stmt2->close();
}
$stmt5->close();
}
}
airfare table image
others expenses table image
My current problem is now how to handle if table in other expense tab is empty? because when i try to submit form and fill in all the input except for the others expense tab table which i let it empty. when i submit the form, the empty row in other expense tab table is insert in database table as well..
I am using php mysql pdo in here and trying to concatenate fname and lname but nothing going right am encountering {"error":true,"error_msg":"Unknown error occurred in registration!"} ..plzz help me out,pardon me if am wrong
.php
<?php
/*
starts with database connection
and gives out the result of query
in json format
*/
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
//proceed if fields are not empty
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['mname']) && !empty($_POST['lname']) && !empty($_POST['pob']) && !empty($_POST['dob']) && !empty($_POST['qualification']) && !empty($_POST['pg']) && !empty($_POST['pgy']) && !empty($_POST['graduation']) && !empty($_POST['gy']) && !empty($_POST['schooling']) && !empty($_POST['sy']) && !empty($_POST['religion']) && !empty($_POST['caste']) && !empty($_POST['subcaste']) && !empty($_POST['familyname']) && !empty($_POST['fathername']) && !empty($_POST['mothername']) && !empty($_POST['brothers']) && !empty($_POST['sisters'])){
//reciving the post parameters
$salutation =$_POST['salutation'];
$fname = trim($_POST['fname']);
$mname = trim($_POST['mname']);
$lname = trim($_POST['lname']);
$pob = trim($_POST['pob']);
$dob = trim($_POST['dob']);
$qualification = trim($_POST['qualification']);
$pg = trim($_POST['pg']);
$pgy = trim($_POST['pgy']);
$graduation = trim($_POST['graduation']);
$gy = trim($_POST['gy']);
$schooling = trim($_POST['schooling']);
$sy = trim($_POST['sy']);
$religion = trim($_POST['religion']);
$caste = trim($_POST['caste']);
$subcaste = trim($_POST['subcaste']);
$familyname = trim($_POST['familyname']);
$fathername = trim($_POST['fathername']);
$mothername = trim($_POST['mothername']);
$brothers = trim($_POST['brothers']);
$sisters = trim($_POST['sisters']);
/*
validation process
begins from here
*/
// create a new user profile
$user = $db->storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters);
if ($user){
// user stored successfully as post params passed
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["salutation"] = $user["salutation"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["mname"] = $user["mname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["pob"] = $user["pob"];
$response["user"]["dob"] = $user["dob"];
$response["user"]["qualification"] = $user["qualification"];
$response["user"]["pg"] = $user["pg"];
$response["user"]["pgy"] = $user["pgy"];
$response["user"]["graduation"] = $user["graduation"];
$response["user"]["gy"] = $user["gy"];
$response["user"]["schooling"] = $user["schooling"];
$response["user"]["sy"] = $user["sy"];
$response["user"]["religion"] = $user["religion"];
$response["user"]["caste"] = $user["caste"];
$response["user"]["subcaste"] = $user["subcaste"];
$response["user"]["familyname"] = $user["familyname"];
$response["user"]["fathername"] = $user["fathername"];
$response["user"]["mothername"] = $user["mothername"];
$response["user"]["brothers"] = $user["brothers"];
$response["user"]["sisters"] = $user["sisters"];
$response["user"]["uuid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
this is the database part using pdo.
php
public function storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters){
try {
$characters = '0123456789';
$uuid = '';
$random_string_length = 6;
for ($i = 0; $i < $random_string_length; $i++) {
$uuid .= $characters[rand(0, strlen($characters) - 1)];
}
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
//concatenate the strings
$sql = "UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname)";
$dbh = $this->db->prepare($sql);
$dbh->execute();
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
The concatenation of first name and last name in your INSERT query is incorrect. Use a $fullname variable to specify full name of the person, and use that variable in your INSERT query. That way you won't have to update the row because you have already inserted the row with the correct full name.
Your code should be like this:
// your code
$fullname = $fname . ", " . $lname;
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fullname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
// your code
If I understand the issue properly, the values are not being inserted because you are executing, instead, a SELECT statement. SELECT statements do not modify table data. You would instead do something like this:
UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
Note, this would update the entire table....
This will fill in a pre-existing column with the new concatenated value made from the fname and lname values of each row.
Of course, if your table does not currently have a column for fullname, add one:
ALTER TABLE profile_info ADD COLUMN fullname varchar(25);
UPDATE
Take this line out:
$sql = UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
And change this line:
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
You'll see I added 'fullname' in the columns list, and this in the values list: '$fname'.', '.'$lname',
using PHP's concatenation operator .
The correct way to accomplish this is to simply concatenate the values and insert them at the very same time you insert the rest of the values. Let me know if that does it for you.
A side note, editing your original code does make the question more confusing for viewers who came in after the edits were made. Consider adding notes about any edits to the code, instead of editing the original example.
i have a form for job post now whenever user enters data and i use mysql real escape string it insert blank data in mysql what could be the reason?
here is the code of site. the thing is i can't trust user input that's why i want to use mysql_real_escape string . i have been trying and changing codes from 2 hours but none of them gave me good result!
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
$userid1 = $_SESSION['username2'];
$email= test_input($_POST['email']);
$salary= test_input($_POST['salary']);
$job_title = test_input($_POST['jtitle']);
$company = test_input($_POST['company']);
$company = mysql_real_escape_string($_POST['company']);
$location = test_input($_POST['location']);
$jobtype = test_input($_POST['jobtype']);
$description = test_input($_POST['description']);
$closingdate = test_input($_POST['closingdate']);
$application = test_input($_POST['application']);
$phone = test_input($_POST['phone']);
$company_description = test_input($_POST['company_description']);
$co_video = test_input($_POST['co_video']);
$website = test_input($_POST['website']);
$fbid = test_input($_POST['fbid']);
$twid = test_input($_POST['twid']);
function create_slug($string){
$replace = '-';
$string = strtolower($string);
//replace / and . with white space
$string = preg_replace("/[\/\.]/", " ", $string);
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//remove multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//convert whitespaces and underscore to $replace
$string = preg_replace("/[\s_]/", $replace, $string);
//limit the slug size
$string = substr($string, 0, 100);
//slug is generated
return $string;
}
$string = $job_title;
$slug = create_slug($string);
$query = mysqli_query($con, "SELECT * FROM `job` WHERE `url` LIKE '".$slug."%'");
$exists = mysqli_fetch_array(mysqli_query($con,"SELECT count(id) as notify FROM `job` where `url` LIKE '".$slug."%'"));
$notify = $exists['notify'];
if ($notify > 0)
{
$new_number = $notify + 1;
$newslug = $slug."-".$new_number;
$run = mysqli_query($con, "INSERT INTO `job` (`email`, `salary`, `username`, `job_title`, `company_name`, `location`, `job_type`, `description`, `phone`, `closing_date`, `application_url`, `company_description`, `video`, `website`, `fb`, `tw`, `category`, `url`) VALUES ('".$email."', '".$salary."', '".$userid1."', '".$job_title."', '".$company."', '".$location."', '".$jobtype."', '".$description."', '".$phone."', '".$closingdate."', '".$application."', '".$company_description."', '".$co_video."', '".$website."', '".$fbid."', '".$twid."', '".$lt."' , '".$newslug."')");
} else{
$run = mysqli_query($con, "INSERT INTO `job` (`email`, `salary`, `username`, `job_title`, `company_name`, `location`, `job_type`, `description`, `phone`, `closing_date`, `application_url`, `company_description`, `video`, `website`, `fb`, `tw`, `category`, `url`) VALUES ('".$email."', '".$salary."', '".$userid1."', '".$job_title."', '".$company."', '".$location."', '".$jobtype."', '".$description."', '".$phone."', '".$closingdate."', '".$application."', '".$company_description."', '".$co_video."', '".$website."', '".$fbid."', '".$twid."', '".$lt."', '".$slug."')");
well i think you have to use two parameters in mysqli_real_escape_string
but first you have to create the first parameter by setting connection with database it should be like
<?php
//for setting up connection with database
$conn=mysqli_connect('yourhostname','your mysql user name','your mysql password','your database');
//than try using this parameter in mysqlirealescapestring
$data=mysqli_real_escape_string($conn,$data);
?>
i hope that this could work
i made an admission form, trying to save the inform to database, it is working and saving all the information into database but empty query is not working.
<?php
include 'authentication.php';
include 'includes/dbConnect.php';
$class = $_POST['class'];
$category = $_POST['category'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$date_of_birth = $_POST['date-of-birth'];
$mark_of_identification = $_POST['mark-of-identification'];
$religion = $_POST['religion'];
$father_name = $_POST['father-name'];
$occupation = $_POST['occupation'];
$army_no = $_POST['army-no'];
$rank = $_POST['rank'];
$regt = $_POST['regt'];
$unit = $_POST['unit'];
$contact = $_POST['contact'];
$guardian = $_POST['guardian'];
$guardian_occupation = $_POST['guardian-occupation'];
$mother = $_POST['mother'];
$mother_occupation = $_POST['mother-occupation'];
$present_adress = $_POST['present-adress'];
$permanent_adress = $_POST['permanent-adress'];
$school = $_POST['school'];
$registration_number = $_POST['registration-no'];
$exam = $_POST['exam'];
$ssc_school = $_POST['ssc-school'];
$ssc_year = $_POST['ssc-year'];
$ssc_total_marks = $_POST['ssc-total-marks'];
$ssc_marks = $_POST['ssc-marks'];
$ssc_grade = $_POST['ssc-grade'];
$ssc_percentage = $_POST['ssc-percentage'];
$ssc_sub = $_POST['ssc-sub'];
$exam2 = $_POST['exam2'];
$ssc_ii_school = $_POST['ssc-ii-school'];
$ssc_year_two = $_POST['ssc-year-two'];
$ssc_ii_total_marks = $_POST['ssc-ii-total-marks'];
$ssc_ii_marks = $_POST['ssc-ii-marks'];
$ssc_ii_grade = $_POST['ssc-ii-grade'];
$ssc_ii_percentage = $_POST['ssc-ii-percentage'];
$ssc_sub2 = $_POST['ssc-sub2'];
$exam3 = $_POST['exam3'];
$o_level_school = $_POST['o-level-school'];
$o_level = $_POST['o-level'];
$o_level_total_marks = $_POST['o-level-total-marks'];
$o_level_marks = $_POST['o-level-marks'];
$o_level_grade = $_POST['o-level-grade'];
$o_level_percentage = $_POST['o-level-percentage'];
$o_level_sub = $_POST['o-level-sub'];
$exam4 = $_POST['exam4'];
$hssc_school = $_POST['hssc-school'];
$hssc_year = $_POST['hssc-year'];
$hssc_total_marks = $_POST['o-level-marks'];
$hssc_marks = $_POST['hssc-marks'];
$hssc_grade = $_POST['hssc-grade'];
$hssc_percentage = $_POST['hssc-percentage'];
$hssc_sub = $_POST['hssc-sub'];
$admission_number = $_POST['admission-number'];
$admission_date = $_POST['admission-date'];
$roll_number = $_POST['roll-number'];
$section = $_POST['section'];
if ($name == '' || $category == '')
{
$myURL = 'error.php?eType=pass';
header('Location: '.$myURL);
exit;
}
$sql1 = mysql_query("INSERT INTO `school`.`students` (`S_No`, `Roll_No`, `Name`, `Father_Name`, `Class`, `Section`, `Gender`, `Mark_of_identification`, `Date_of_birth`, `Religion`, `Admission_date`, `name_of_last_school`, `Board_registration_number`, `student_category`) VALUES (NULL, '$roll_number', '$name', '$father_name', '$class', '$section', '$gender', '$mark_of_identification', '$date_of_birth', '$religion', '$admission_date', '$school', '$registration_number', '$category');") or die("SELECT Error: ".mysql_error());
$sql2 = mysql_query("INSERT INTO `school`.`parents` (`S_No`, `Roll_no`, `Father_name`, `Father_occupation`, `Army_number`, `Rank`, `Corps`, `Unit`, `Contact_number`, `Guardian_name`, `Guardian_occupation`, `Mother_name`, `Mother_occupation`, `Present_address`, `Permanent_address`) VALUES (NULL, '$roll_number', '$father_name', '$occupation', '$army_no', '$rank', '$regt', '$unit', '$contact', '$guardian', '$guardian_occupation', '$mother', '$mother_occupation', '$present_adress', '$permanent_adress');") or die("SELECT Error: ".mysql_error());
$sql3 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam', '$ssc_school', '$ssc_year', '$ssc_total_marks','$ssc_marks', '$ssc_grade', '$ssc_percentage', '$ssc_sub', '$roll_number');")
or die("SELECT Error: ".mysql_error());
if ($exam2!='');
$sql4 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam2', '$ssc_ii_school', '$ssc_year_two', '$ssc_ii_total_marks','$ssc_ii_marks', '$ssc_ii_grade', '$ssc_ii_percentage', '$ssc_sub2', '$roll_number');")
or die("SELECT Error: ".mysql_error());
if ($exam3!='');
$sql5 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam3', '$o_level_school', '$o_level', '$o_level_total_marks','$o_level_marks', '$o_level_grade', '$o_level_percentage', '$o_level_sub', '$roll_number');")
or die("SELECT Error: ".mysql_error());
if ($exam4!='');
$sql6 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam4', '$hssc_school', '$hssc_year', '$hssc_total_marks','$hssc_marks', '$hssc_grade', '$hssc_percentage', '$hssc_sub', '$roll_number');")
or die("SELECT Error: ".mysql_error());
if($sql1 && $sql2 && $sql3 && $sql4 && $sql5 && $sql6 )
{
$myURL = 'success.php?sType=insert';
header('Location: '.$myURL);
exit;
}
else
echo "Try again!";
?>
Initially i am checking only two fields, later i will check all the fields. Even if they are filled it give error. if i try this without checking empty field query it is working and saving information. Kindly guide me where i am doing wrong.
Thanks in advance
You are not using if ($exam2!='') if ($exam3!='') if ($exam4!='') conditions properly try to use them like that
if (!empty($exam2)){
$sql4 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam2', '$ssc_ii_school', '$ssc_year_two', '$ssc_ii_total_marks','$ssc_ii_marks', '$ssc_ii_grade', '$ssc_ii_percentage', '$ssc_sub2', '$roll_number');")
or die("SELECT Error: ".mysql_error());
}
if (!empty($exam3)){
$sql5 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam3', '$o_level_school', '$o_level', '$o_level_total_marks','$o_level_marks', '$o_level_grade', '$o_level_percentage', '$o_level_sub', '$roll_number');")
or die("SELECT Error: ".mysql_error());
}
if (if (!empty($exam4)){
$sql6 = mysql_query("INSERT INTO `school`.`academic` (`S_No`, `Exam`, `School`, `Year`, `Total_marks`, `Marks_obtained`, `Grade`, `Percentage`,`Major_subjects`, `Roll_no`) VALUES (NULL, '$exam4', '$hssc_school', '$hssc_year', '$hssc_total_marks','$hssc_marks', '$hssc_grade', '$hssc_percentage', '$hssc_sub', '$roll_number');")
or die("SELECT Error: ".mysql_error());
}
I think you should check your database field Null then try.. it may be work