SQL Insert statement, does not use a $variable's value - php

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

Related

Check to see if record exists before database insert [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 2 years ago.
I have a database that contains more than 640,000 records that I update every week with data from a JSON file. What I want to do is only load records into the database that do not currently exists. My script below works on small amounts of data but when I try to load a large file it times out (I get a 500 Internal Server Error). Is there a better way to do this?
<?php
set_time_limit(0);
ini_set('memory_limit','2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
foreach($records as $record) {
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT * FROM oer_search WHERE title=:title AND author=:author AND source=:source");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
}
}
if($insert){
echo "<p><span class='recordInserted'><em>$name was successfully inserted into SOAR.</em></span></p>";
}
else {
echo "<p><span class='recordInserted'><em>Record(s) already exist in SOAR.</em></span></p>";
}
echo "</div>";
?>
I could not comment, I wrote as an answer because my score was not enough. can you change it like this and try it?
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
or
<?php
if(!session_id()) session_start();
ini_set('memory_limit', '2000M');
$url = 'json/OERrecordstest.json';
$contents = file_get_contents($url);
$records = json_decode($contents, true);
include("../config.php");
echo "<div class='card card-body'>";
if (!$_SESSION["records"]) {
foreach ($records as $record) {
$_SESSION["records"][$record["id"]] = $records;
}
}
$i = 0;
foreach ($_SESSION["records"] as $record) {
$i++;
if ($i > 1000) break;
$type = $record['type'];
$name = $record['title'];
$title = addslashes($name);
$creator = $record['author'];
$author = addslashes($creator);
$link = addslashes($record['link']);
$origin = $record['source'];
$source = addslashes($origin);
$description = addslashes($record['description']);
$base_url = $record['base_url'];
$isbn_number = $record['isbn_number'];
$e_isbn_number = $record['e_isbn_number'];
$publication_date = $record['publication_date'];
$license = $record['license'];
$subject = addslashes($record['subject']);
$image_url = $record['image_url'];
$review = $record['review'];
$language = $record['language'];
$license_url = $record['license_url'];
$publisher = addslashes($record['publisher']);
$publisher_url = $record['publisher_url'];
$query = $conn->prepare("SELECT id FROM oer_search WHERE title=:title AND author=:author AND source=:source limit 1");
$query->bindParam(":title", $name);
$query->bindParam(":author", $creator);
$query->bindParam(":source", $origin);
$query->execute();
if ($query->rowCount() == 0) {
$insert = $conn->prepare("INSERT INTO oer_search (type, title, author, link, source, description, base_url, isbn_number, e_isbn_number, publication_date, license, subject, image_url, review, language, license_url, publisher, publisher_url) VALUES ('$type', '$title', '$author', '$link', '$source', '$description', '$base_url', '$isbn_number', '$e_isbn_number', '$publication_date', '$license', '$subject', '$image_url', '$review', '$language', '$license_url', '$publisher', '$publisher_url')");
$insert->execute();
unset($_SESSION["records"][$record["id"]]);
}
}
print "remaining data :". count($_SESSION["records"]);
?>
Tipps to speed up mass-imports:
Move your SQL prepare outside of the loop (you only have to do it once)
Collect data to insert into batches of 1000 (for example.. usually alot more possible)
Use transactions / disable Index calculation during insert
Find duplicates with a lookup array from existing data (don't query the database for each row of your import)
In general: Avoid SQL queries in Loops
hope that helps a bit

Data not inserting to database table

When I choose the expandable radio button and press the save button it should save its data to inventory_status table but the data wont insert into the inventory_status table. I've seen similar questions but still couldn't figure out the cause of the problem.
<?php
if($_POST['save']){
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$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."')");
}
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>
";
}
}
This is the table structure of our inventory_status table:
I found one issue on your following query. sms_request.date should be sms_request_date
$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')");
Other thing
All these '".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')" variables are not defined. so you have to take this condition in loop.
For i.e.
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];
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$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."')");
}

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.

Empty query not working in PHP

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

How to upload multiple images but with same last_id?

I am trying to insert multiple images with the same last_id
But I am having a problem the code does not do exactly what am looking for
I have two tables one is user table and the image’s table so I want each user when he or she uploads images they should grab the last ids and use them in image’s table but also each image will be having a unique image Id . in the user table there user_id as primary key and in the image table there is user_id as a fk and image_d pk . bellow is my code .
<?php
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
}}
?>
<?php
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$user,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo
(title, firstname, lastname, nickname, idnumber, client_code,
company, country, city, province, address, cell,
tel, webaddress, satifiedstatus, email, job_approval, cash_with_vat,
cash_paid, date_registered,user_id)
VALUES(:title,:firstname,:lastname,:nickname,:idnumber,:client_code,
:company,:country,:city,:province,:address,
:cell,:tel,:webaddress,:satifiedstatus, :email, :job_approval,
:cash_with_vat,:cash_paid, :date_registered,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname,
':nickname'=>$nickname,
':idnumber'=>$idnumber,
':client_code'=>$client_code,
':company'=>$company,
':country'=>$country,
':city'=>$city,
':province'=>$province,
':address'=>$address,
':cell'=>$cell,
':tel'=>$tel,
':webaddress'=>$webaddress,
':satifiedstatus'=>$satifiedstatus,
':email'=>$email,
':job_approval'=>$job_approval,
':cash_with_vat'=>$cash_with_vat,
':cash_paid'=>$cash_paid,
':date_registered'=>$date_registered
));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
##############################category
$cats = $vals = array();
foreach ((array) $_POST['category_name'] as $cat) {
if ('' !== ($cat = trim($cat))) {
$cats[] = $cat;
$vals[] = "({$last_id}, ?)";
}
}
################################################
$sql = 'INSERT INTO tish_catigory (user_id, category_name) VALUES'. join(',', $vals);
$sth = $con->prepare($sql);
foreach ($cats as $i => $cat) {
$sth->bindValue($i+1, $cat, PDO::PARAM_STR);
}
$sth->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
var_dump($last_id);
?>
That should work I tested it and it worked
<?php
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$user,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo
(title, firstname, lastname, nickname, idnumber, client_code,
company, country, city, province, address, cell,
tel, webaddress, satifiedstatus, email, job_approval, cash_with_vat,
cash_paid, date_registered,user_id)
VALUES(:title,:firstname,:lastname,:nickname,:idnumber,:client_code,
:company,:country,:city,:province,:address,
:cell,:tel,:webaddress,:satifiedstatus, :email, :job_approval,
:cash_with_vat,:cash_paid, :date_registered,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname,
':nickname'=>$nickname,
':idnumber'=>$idnumber,
':client_code'=>$client_code,
':company'=>$company,
':country'=>$country,
':city'=>$city,
':province'=>$province,
':address'=>$address,
':cell'=>$cell,
':tel'=>$tel,
':webaddress'=>$webaddress,
':satifiedstatus'=>$satifiedstatus,
':email'=>$email,
':job_approval'=>$job_approval,
':cash_with_vat'=>$cash_with_vat,
':cash_paid'=>$cash_paid,
':date_registered'=>$date_registered
));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
}}
##############################category
$cats = $vals = array();
foreach ((array) $_POST['category_name'] as $cat) {
if ('' !== ($cat = trim($cat))) {
$cats[] = $cat;
$vals[] = "({$last_id}, ?)";
}
}
################################################
$sql = 'INSERT INTO tish_catigory (user_id, category_name) VALUES'. join(',', $vals);
$sth = $con->prepare($sql);
foreach ($cats as $i => $cat) {
$sth->bindValue($i+1, $cat, PDO::PARAM_STR);
}
$sth->execute();
############# property table##########################################################
/*$property ="INSERT INTO tish_propertyinfo(user_id,date_registered)
VALUES($last_id,:date_registered)";
$property_insert = $con->prepare($images);
$property_insert->execute(array(':date_registered'=>$date_created));
*/}catch(PDOException $e){
echo $e->getMessage();
}
#for the insert check boxes
var_dump($last_id);
#images
?>

Categories