Concatenation of strings not working..! - php

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.

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++;
}
}

Submit two table of data in one form

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..

mysql_multi_query inside a foreach loop

I try to parse a xml file and store each node to a mysql db. The problem is that it store the data in the first loop and returns error in the second time. If I refresh the page it stores the rest data as well.
I try to understand why does it behave in a such way
<?php
try{
$records = simplexml_load_file("file.xml");
} catch (Exception $e){
echo "xml problem";
}
#replace loclhost,user, pass, dbname
$db = mysqli_connect("localhost", "root", "", "project") or die("could not connect:" . mysqli_connect_error());
foreach($records->record as $rec){
$species_location_x = $rec->species_lang;
$species_location_y = $rec->species_long;
$species_abundance = (string)$rec->abundance;
$species_text = (string)$rec->text;
$species_scene_photo = (string)$rec->space_photo;
$species_photo_loc = (string)$rec->specimen_photo;
$site_name = (string)$rec->site->sitename;
$site_location = (string)$rec->site->sitelocation;
$site_description = (string)$rec->site->sitedescription;
$user_name = (string)$rec->user->lastname;
$user_phone = (string)$rec->user->namephone;
$user_email = (string)$rec->user->useremail;
$species_name = (string)$rec->species->species_name;
#print_r($species_location_x." ".$species_location_y." ".$species_abundance." ".$species_text." ".$species_scene_photo." ".$species_photo_loc);
#print_r($site_name." ".$site_location." ".$site_description);
#print_r($user_name." ".$user_phone." ".$user_email);
#print_r($species_name);
$multiq = "INSERT INTO users (user_name, user_phone, user_email)
VALUES ('$user_name', '$user_phone', '$user_email');" ;
$multiq .= "INSERT INTO records (user_name, record_location, record_abundance, record_text, record_scene_photo_location, record_specimen_photo_location )
VALUES ( '$user_name',
GeomFromText('point($species_location_x $species_location_y)'),
'$species_abundance',
'$species_text',
'$species_scene_photo',
'$species_photo_loc');" ;
$multiq .= "INSERT INTO species (species_name, records_id )
VALUES ( '$species_name', (select record_id from records where user_name = '$user_name' and record_abundance = '$species_abundance' and record_text = '$species_text'));" ;
$multiq .= "INSERT INTO sites (site_name, site_location, site_description, species_id)
VALUES ('$site_name', '$site_location', '$site_description', (select species_id from species where species_name='$species_name'));";
if(mysqli_multi_query($db, $multiq)){
echo "records added successfully\n";
}
else{
echo "problem";
}
}
mysqli_close($db);

Having issue PHP-MySQL signup form

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');

Categories