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
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 variable named $src, that does have a value, (I checked it before the insert). But when I execute the insert statement, the field is saved as blank "";
I don't know what the problem is, I have a text field in my DB set to accept any kind of character... and still it did not work.
Someone help me please.
<?php
include 'fimg.class.php';
require('cone.php');
$id = $_POST['id'];
$tipo_bolsa = $_POST['tipo_bolsa'];
$titulo = $_POST['titulo'];
$imagen = $_POST['imagen'];
$descripcion = $_POST['descripcion'];
$categoria = $_POST['categoria'];
$fecha = $_POST['fecha'];
$sueldo = $_POST['sueldo'];
$idP = $_POST['idP'];
$src = "";
if (isset($_FILES["file"]))
{
$file = $_FILES["file"];
$nombre = FIMG::getUniqueName();
$tipo = $file["type"];
$ruta_provisional = $file["tmp_name"];
$size = $file["size"];
$carpeta = "upload/";
$src = $carpeta.$nombre;
move_uploaded_file($ruta_provisional, $src);
$img = new FIMG($src);
$img->setWidth(500);
$img->save(null,FJPG);
$img->close();
echo "<img src='$src'>";
}
echo $src;
$con = Conectar();
$sql = "INSERT INTO bolsa (id, tipo_bolsa, titulo, imagen, descripcion, categoria, fecha, sueldo) VALUES (:id, :tipo_bolsa, :titulo, '$src', :descripcion, :categoria, :fecha, :sueldo)";
echo "<br>".$sql; //Checkpoint
//Variable $src does have a value i check it (img_9uf87d8fwhatever7asd7f89adsf.jpg) but when i do the insert the field inserted is empty ""
$q = $con->prepare($sql);
$q->execute(array(':id'=>$id, ':tipo_bolsa'=>$tipo_bolsa, ':titulo'=>$titulo, ':descripcion'=>$descripcion, ':categoria'=>$categoria, ':fecha'=>$fecha, ':sueldo'=>$sueldo));
?>
This is what i get when i print the sentence, before send:
INSERT INTO bolsa (id, tipo_bolsa, titulo, imagen, descripcion, categoria, fecha, sueldo) VALUES (:id, :tipo_bolsa, :titulo, 'upload/img_20160108154835d45f49a8db1d6f1f4d2e29.jpg', :descripcion, :categoria, :fecha, :sueldo)
And this is my db info
You have:
$sql = "INSERT INTO bolsa (id, tipo_bolsa, titulo, imagen, descripcion, categoria, fecha, sueldo) VALUES (:id, :tipo_bolsa, :titulo, '$src', :descripcion, :categoria, :fecha, :sueldo)";
$q = $con->prepare($sql);
$q->execute(array(':id'=>$id, ':tipo_bolsa'=>$tipo_bolsa, ':titulo'=>$titulo, ':descripcion'=>$descripcion, ':categoria'=>$categoria, ':fecha'=>$fecha, ':sueldo'=>$sueldo));
Why are you treating $src differently from the rest? That is, why not:
$sql = "INSERT INTO bolsa (id, tipo_bolsa, titulo, imagen, descripcion, categoria, fecha, sueldo) VALUES (:id, :tipo_bolsa, :titulo, :src, :descripcion, :categoria, :fecha, :sueldo)";
$q = $con->prepare($sql);
$q->execute(array(':id'=>$id, ':tipo_bolsa'=>$tipo_bolsa, ':titulo'=>$titulo, ':src'=>$src, ':descripcion'=>$descripcion, ':categoria'=>$categoria, ':fecha'=>$fecha, ':sueldo'=>$sueldo));
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.
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);.
I tried inserting an array into the database. It does inserts but only with the admin = 0 && special admin != 1. When I try altering the database in which i will set admin to 3 and special admin to != 1 it does not insert at all.
Needed help here so here's the code I have so far
$ques = "SELECT * FROM ip_restriction where ipnum = '".$ip_2."'";
$ress = mysql_query($ques);
if ($roww = mysql_fetch_array($ress)) {
if ($row ['admin'] == 0 && $row['special_admin']!=1)
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'AGENT', 'Admin', NOW())";
}
elseif ($row ['admin'] == 0 && $row['special_admin']==1 )
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'AGENT', 'Admin', NOW())";
}
elseif ($row ['admin'] == 3 && $row['special_admin']!=1 )
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'CLIENT', 'Admin', NOW())";
}
elseif ($row ['admin'] == 3 && $row['special_admin']==1 )
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'CLIENT', 'Admin', NOW())";
}
elseif ($row ['admin'] == 4 && $row['special_admin']!=1 )
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'AGENT', 'Admin', NOW())";
}
$ressinput= mysql_query($queinsert);
header('Location: index.php');
}
You can actually try this. bcoz whatever the condition is you are inserting the same values in the DB. So I don't understand the actual meaning of putting the conditions.
$ques = "SELECT * FROM ip_restriction where ipnum = '".$ip_2."'";
$ress = mysql_query($ques);
if ($roww = mysql_fetch_array($ress))
{
$queinsert = "INSERT INTO tblid (ipadd, ipdept, createdby, datecreated)
VALUES ('".$ip_2."', 'AGENT', 'Admin', NOW())";
}
$ressinput= mysql_query($queinsert);
header('Location: index.php');
Try:
$ressinput = mysql_query($queinsert);
if (!$ressinput) {
die('Invalid query: ' . mysql_error());
} else {
header('Location: index.php');
}