Having issue PHP-MySQL signup form - php

After form submission browser shows just blank page. Nothing else. I've enabled error reporting. No error in php logs. Also tried (as you see) echo $sql; die();. Still no result. How to fix it? What's wrong with my code? My php code (which processes signup form data) looks like that
<?php
require '../includes/db.php';
require '../includes/ipurl.php';
require '../includes/common.php';
$page = 'signup';
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit( );
}
if ($_POST['submit'] == 'Tamam') {
$err = array( );
foreach ($_POST as $key => $value) {
$data[$key] = filter($value);
}
if (empty($data['fname']) || strlen($data['fname']) < 2 || empty($data['mname']) || strlen($data['mname']) < 2 || empty($data['lname']) || strlen($data['lname']) < 2) {
$err[ ] = 1;
}
if (!isUserID($data['login'])) {
$err[ ] = 2;
}
if (!isEmail($data['email'])) {
$err[ ] = 3;
}
if (!checkPwd($data['pwd'], $data['pwd2'])) {
$err[ ] = 4;
}
$pwd = PwdHash($data['pwd']);
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$activ_code = rand(1000, 9999);
$email = $data['email'];
$login = $data['login'];
$dob = date('Y-m-d', strtotime($data['dob']));
$age = date("Y") - date('Y', strtotime($data['dob']));
$type = $data['type'];
$rs_duplicate = $db->query("select count(*) as total from users where email='$email' OR login='$login'") or die($db->error);
list($total) = $rs_duplicate->fetch_row();
if ($total > 0) {
$err[ ] = 5;
}
if (isset($type)) {
if ($type == 1) {
$region = $data['region'];
$school = $data['school'];
$class = $data['class'];
$group = 0;
$subject = 0;
$university = 0;
$profession = 0;
}
if ($type == 2) {
$group = $data['group'];
$region = $data['region'];
$school = $data['school'];
$class = $data['class'];
$subject = 0;
$university = 0;
$profession = 0;
}
if ($type == 3) {
$group = 0;
$region = 0;
$school = 0;
$class = 0;
$subject = 0;
$university = $data['university'];
$profession = $data['profession'];
}
if ($type == 4) {
$group = 0;
$region = 0;
$school = 0;
$class = 0;
$university = 0;
$profession = 0;
$subject = $data['subject'];
}
}
if (!isset($type)) {
$err[ ] = 9;
}
if (empty($err)) {
$sql = "INSERT INTO users
(level,fname, mname, lname, dob, age, reg_date, phone, email, login, pwd, type, `group`, region, school, class, ip, subject, ban, university, profession, activation_code)
VALUES
('1','$data[fname]', '$data[mname]', '$data[lname]', '$dob', '$age', now(), '$data[phone]', '$email', '$login', '$pwd', '$type', '$group', '$region', '$school', '$class', '$ip', '$subject', NULL, '$university', '$profession', '$activ_code')";
echo $sql; die();
$result = $db->query($sql) or die(printf("Bazaya daxiletmə zamanı səhv: %s\n", $db->error));
$id = $db->insert_id;
$md5_id = md5($id);
$db->query("update users set md5_id='$md5_id' where id='$id'") or die(printf("Bazaya daxiletmə zamanı səhv: %s\n", $db->error));
include "../includes/success.php";
}
} else if (!empty($err)) {
include "../includes/error.php";
}
?>
By the way function filter from common.php sanitizing all posts
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}

I think your check for a non-empty error array should be moved up a step to right after where you check for if there are any errors.
...
if (empty($err)) {
$sql = "INSERT INTO users
(level,fname, mname, lname, dob, age, reg_date, phone, email, login, pwd, type, `group`, region, school, class, ip, subject, ban, university, profession, activation_code)
VALUES
('1','$data[fname]', '$data[mname]', '$data[lname]', '$dob', '$age', now(), '$data[phone]', '$email', '$login', '$pwd', '$type', '$group', '$region', '$school', '$class', '$ip', '$subject', NULL, '$university', '$profession', '$activ_code')";
echo $sql; die();
$result = $db->query($sql) or die(printf("Bazaya daxiletmə zamanı səhv: %s\n", $db->error));
$id = $db->insert_id;
$md5_id = md5($id);
$db->query("update users set md5_id='$md5_id' where id='$id'") or die(printf("Bazaya daxiletmə zamanı səhv: %s\n", $db->error));
include "../includes/success.php";
} else if (!empty($err)) {
include "../includes/error.php";
}
}

I would strongly suggest getting XDebug installed on your development machine, and use an IDE like NetBeans, Eclipse PDT or even better PHPStorm to try and set breakpoints inside your code, and see at what point it breaks.
You can get XDebug here: http://xdebug.org
Alternatively, take a step back, and add the following line
exit("i was here!");
at line 1, to first determine if the script is actually running, and if you can see the output, step by step, move it a line down, save and rerun the script, rinse and repeat until it breaks.
I suppose as well, although you have error reporting turned on, there could be a line of code in any of the 3 files you are including that turns it back off again like in this snippet:
error_reporting(0);
or even:
ini_set('display_errors','Off');

Related

PHP MYSQL ODBC connection succesfull but not retrieving data

so i moved all the data from mysql control center(outdated) to workbench
all the connections seems to be successful but i cant retrieve any data while loggin in.its blank page..was working before i migrated everything over
see the code and screenshot below..any help would be appreciated
enter image description here
include('dbconnect.php');
if(isset($_POST['submit']))
{
$error_username = '';
$error_password = '';
$error_general = '';
$usernamedd = $_POST['username'];
$passworddd = $_POST['password'];
if($usernamedd == '')
$error_username = '<font color="red">- No username entered</font>';
if($passworddd == '')
$error_password = '<font color="red">- No password entered</font>';
if($usernamedd != '' && $passworddd != '')
{
//echo "SELECT username,firstname,lastname,perm_calendar,perm_users,perm_market,perm_newsletter FROM emp_tbl WHERE username='$usernamedd' AND password='$passworddd'";
$result = odbc_exec($conn, "SELECT username,firstname,lastname,perm_calendar,perm_users,perm_market,perm_newsletter,perm_topagents FROM emp_tbl WHERE (username='$usernamedd' OR email='$usernamedd') AND MD5(password)=MD5('$passworddd') LIMIT 1");
//echo "SELECT username,firstname,lastname,perm_calendar,perm_users,perm_market,perm_newsletter FROM emp_tbl WHERE username='$usernamedd' AND MD5(password)=MD5('$passworddd') LIMIT 1";
//echo "SELECT username FROM staff WHERE username='$username' AND dept='Admin'<br><br>";
$_username = odbc_result($result, "username");
$_fullname = odbc_result($result, "firstname").' '.substr(odbc_result($result, "lastname"),0,1).'.';
$_perm_calendar = odbc_result($result, "perm_calendar");
$_perm_users = odbc_result($result, "perm_users");
$_perm_market = odbc_result($result, "perm_market");
$_perm_newsletter = odbc_result($result, "perm_newsletter");
$_perm_topagents = odbc_result($result, "perm_topagents");
//echo "<br><br>username: ".$_username;
//echo "<br>full name: ".$_fullname;
//echo "<br>perm_calendar: ".$_perm_calendar;
//echo "<br>per_users: ".$_perm_users;
//echo "<br>perm_market: ".$_perm_market;
//echo "<br>perm_newsletter: ".$_perm_newsletter;
if($_username != '')
{
if(isset($_POST['save']))
{
setcookie("username",odbc_result($result, 'username'),time()+604000);
$resultlog = odbc_exec($conn, "INSERT INTO logs_login (date, file, username, pwd, description, type, ip) VALUES (NOW(), '$file', '$usernamedd', '$passworddd', 'Success : 7 days', 'login', '$ip')");
}
else
{
setcookie("username",odbc_result($result, 'username'));
$resultlog = odbc_exec($conn, "INSERT INTO logs_login (date, file, username, pwd, description, type, ip) VALUES (NOW(), '$file', '$usernamedd', '$passworddd', 'Success : Browser Session', 'login', '$ip')");
}
$_username=odbc_result($result, 'username');
$logged_in = 1;
header("Location: admin_directory.php");
}
else
{
$logged_in = 0;
$error_general = '<font color="red">- No such user or invalid password</font>';
$resultlog = odbc_exec($conn, "INSERT INTO logs_login (date, file, username, pwd, description, type, ip) VALUES (NOW(), '$file', '$usernamedd', '$passworddd', 'Failure: Incorrect user/pwd', 'login', '$ip')");
}
}
}

PHP Insert into PostgreSQL

So it's probably a really stupid/basic question, but i have this simple PHP function (which works) and inserts data into a PostgreSQL DB.
My issue is when it encounters specific data;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = $csvfile[$x]['email'];
$name = $csvfile[$x]['name'];
$surname = $csvfile[$x]['surname'];
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
$x++;
}
}
And while this works, it falls over with a surname such as:
O'hare
And obviously this occurs because then the PHP code comes out as:
...VALUES ('john#example.com', 'John', 'O'hare')";
but im not sure of how i should be structuring the PHP to allow for this.
Try this:
function insertData($pg, $csvfile) {
$nbr = count(file($csvfile));
for($i=0; $i<$nbr; $i++) {
$email = pg_escape_string( $csvfile[$i]['email'] );
$name = pg_escape_string( $csvfile[$i]['name'] );
$surname = pg_escape_string( $csvfile[$i]['surname'] );
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
if (!$result) {
echo "Error while executing the query: " . $query;
exit;
}
}
}
You need to escape the string parameters. And it is much better if you can use PDO extension, because prepared statements can take care of escaping for you and also helps with preventing SQL injection and some other security concerns.
function insertData(PDO $dbh, $csvfile) {
$x = 0;
foreach ($csvfile as $data)
{
$query = "INSERT INTO users (email, name, surname) VALUES (?, ?, ?)";
$params = [
$csvfile[$x]['email'],
$csvfile[$x]['name'],
$csvfile[$x]['surname']
];
$statement = $pdo->prepare($query);
$statement->execute();
$x++;
}
}
PDO::prepare
PDOStatement::execute
Solution using prepared query
function insertData($dbname, $tbname, $csvfile)
{
$result = [];
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=$dbname");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'INSERT INTO $1 (email, name, surname) VALUES ($2, $3, $4)');
// Execute the prepared query. Note that it is not necessary to escape
foreach ($csvfile as $data)
{
$email = $data['email'];
$name = $data['name'];
$surname = $data['surname'];
$query = "";
$result[] = pg_execute($dbconn, "my_query", array($tbname, $email, $name, $surname));
}
if (in_array(false, $result) )
return false;
else
return true;
}
$dbname = "your dbname";
$tbname = "name of table";
$csvFile = [];
if (insertData($dbname, $tbname, $csvFile))
echo "Data inserted";
else
echo "Data not inserted";
So i took note of the suggestions from #Karsten Koop and #TOH19, and came up with this code which is working;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = pg_escape_string($csvfile[$x]['email']);
$name = pg_escape_string($csvfile[$x]['name']);
$surname = pg_escape_string($csvfile[$x]['surname']);
$query = "INSERT INTO users (email, name, surname) VALUES ('".$email."', '".$name."', '".$surname."')";
$result = pg_query($pg, $query);
$x++;
}
}

inserting record if count of column is less than two else not inserting into mysql

just want to add record if count of column is less than 2 for today's date and if count is more than two it should not get insert into the db.It's keep getting added after two records.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$row = mysqli_fetch_assoc($sql);
$sum = $row['totalupload'];
if ($sum < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";
make the connection after count query like this,
$result = mysqli_query($con,$sql);
Try this one hope it will help you.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) as totalupload FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$qry= mysql_query($sql);
$row = mysql_fetch_assoc($qry);
$count = $row['totalupload'];
if ($count < 2 ) {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
} else {
echo"already exist";

Cannot modify header information - headers already sent by [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
<?php
require_once('config.php');
//print_r($_POST);
if(isset($_POST["btnsubmit"]))
{
$flagvalidate = "yes";
//print_r($_POST);
/*foreach($_POST as $key=>$value)
{
if($value=="" && $flagvalidate=="yes")
{
//$flagvalidate = "no";
}
}*/
if($flagvalidate=="yes")
{
$db_fields = "empimage, postapplied, surname, firstname, fathername, dob, age, gender, nationality, religion,mothertongue, caste, subcaste, category, bloodgroup,rhfactor, maritalstatus, name, address, city, state, pincode, telephone, mobile, email, areaofinterest, specialachievements, fitforpost, createdate";
$postvalues = array();
$postvalues[0] = $_POST['hidempimage'];
$postvalues[1] = $_POST['txtpostapplied'];
$postvalues[2] = $_POST['txtsurname'];
$postvalues[3] = $_POST['txtfirstname'];
$postvalues[4] = $_POST['txtfathername'];
$postvalues[5] = $_POST['txtdob'];
$postvalues[6] = $_POST['txtage'];
$postvalues[7] = $_POST['txtgender'];
$postvalues[8] = $_POST['txtnationality'];
$postvalues[9] = $_POST['txtreligion'];
$postvalues[10] = $_POST['txtmothertongue'];
$postvalues[11] = $_POST['txtcaste'];
$postvalues[12] = $_POST['txtsubcaste'];
$postvalues[13] = $_POST['txtcategory'];
$postvalues[14] = $_POST['txtbloodgroup'];
$postvalues[15] = $_POST['txtrhfactor'];
$postvalues[16] = $_POST['txtmaritalstatus'];
$postvalues[17] = $_POST['txtname'];
$postvalues[18] = $_POST['txtaddress'];
$postvalues[19] = $_POST['txtcity'];
$postvalues[20] = $_POST['txtstate'];
$postvalues[21] = $_POST['txtzipcode'];
$postvalues[22] = $_POST['txttelephone'];
$postvalues[23] = $_POST['txtmobile'];
$postvalues[24] = $_POST['txtemail'];
$postvalues[25] = $_POST['txtareaofinterest'];
$postvalues[26] = $_POST['txtspecialachievements'];
$postvalues[27] = $_POST['txtfitforpost'];
$postvalues[28] = time();
$db_values="";
foreach($postvalues as $key=>$value)
{
if($db_values=="")
$db_values.="'".mysql_real_escape_string($value)."'";
else
$db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_employee (".$db_fields.") values (".$db_values.")";
mysql_query($sqlquery);
$currentempid = mysql_insert_id();
$education_db_fields = "empid, exampassed, degree, subjects, university, year, percentagemarks";
for($i=1;$i<=$_POST['hideducationcount'];$i++)
{
$education_postvalues = array();
$education_postvalues[0] = $currentempid;
$education_postvalues[1] = $_POST['txtexampassed'.$i];
$education_postvalues[2] = $_POST['txtdegree'.$i];
$education_postvalues[3] = $_POST['txtedusubjects'.$i];
$education_postvalues[4] = $_POST['txtuniversity'.$i];
$education_postvalues[5] = $_POST['txtyear'.$i];
$education_postvalues[6] = $_POST['txtpercentagemarks'.$i];
$education_db_values="";
foreach($education_postvalues as $key=>$value)
{
if($education_db_values=="")
$education_db_values.="'".mysql_real_escape_string($value)."'";
else
$education_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empeducationdetails (".$education_db_fields.") values (".$education_db_values.")";
mysql_query($sqlquery);
}
$experience_db_fields = "empid, level, name, address, post, fromdate, todate";
for($i=1;$i<=$_POST['hidexperiencecount'];$i++)
{
$experience_postvalues = array();
$experience_postvalues[0] = $currentempid;
$experience_postvalues[1] = $_POST['txtexlevel'.$i];
$experience_postvalues[2] = $_POST['txtexname'.$i];
$experience_postvalues[3] = $_POST['txtexadd'.$i];
$experience_postvalues[4] = $_POST['txtexpostheld'.$i];
$experience_postvalues[5] = $_POST['txtexfromdate'.$i];
$experience_postvalues[6] = $_POST['txtextodate'.$i];
$experience_db_values="";
foreach($experience_postvalues as $key=>$value)
{
if($experience_db_values=="")
$experience_db_values.="'".mysql_real_escape_string($value)."'";
else
$experience_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empexperience (".$experience_db_fields.") values (".$experience_db_values.")";
mysql_query($sqlquery);
}
$reference_db_fields = "empid, name, position, cell, email, address ";
for($i=1;$i<=2;$i++)
{
if ( $_POST['txtrefname'.$i]!='')
{
$reference_postvalues = array();
$reference_postvalues[0] = $currentempid;
$reference_postvalues[1] = $_POST['txtrefname'.$i];
$reference_postvalues[2] = $_POST['txtrefpos'.$i];
$reference_postvalues[3] = $_POST['txtrefcell'.$i];
$reference_postvalues[4] = $_POST['txtrefemail'.$i];
$reference_postvalues[5] = $_POST['txtrefpost'.$i];
$reference_db_values="";
foreach($reference_postvalues as $key=>$value)
{
if($reference_db_values=="")
$reference_db_values.="'".mysql_real_escape_string($value)."'";
else
$reference_db_values.=", '".mysql_real_escape_string($value)."'";
}
$sqlquery = "insert into tbl_empreference (".$reference_db_fields.") values (".$reference_db_values.")";
mysql_query($sqlquery);
}
}
header("Location: registercomplete.php");
}
else
{
exit;
}
//echo "<script>alert('Please fill all the fields in the Application Form!');window.location.href='register.php';</script>";
}
?>
i am getting Warning: Cannot modify header information - headers already sent by (output started at /home/zealouse/public_html/skillhr/config.php:11) in /home/zealouse/public_html/skillhr/registerprocess.php on line 150
can any one help me?
Thanks in advance....
Check if there is any outputs in your config.php file.

Concatenation of strings not working..!

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.

Categories