Data not being inserted mysql - php

I am building a custom CMS for myself and its going great but for some reason the system is not inserting a certain field called categories. I have a table called categories and i am able to insert those categories with no problems.
On my addnewpost.php page I have this form field that lets me select an added Category..
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value=""><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
above all that I have this to inset the data into the database in a table called posts...
<?php
if(isset($_POST["Submit"])){
$posttitle = $_POST["posttitle"];
$Category = $_POST["Category"];
$image = $_FILES["image"]["name"];
$target = "../uploads/".basename($_FILES["image"]["name"]);
$posttext = $_POST["postdescription"];
$admin = "phillip";
date_default_timezone_set("Europe/London");
$CurrentTime=time();
$DateTime=strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($posttitle)){
$_SESSION["ErrorMessage"] = "Post title cannot be empty";
redirect_to("addnewpost.php");
} elseif (strlen($posttitle)<10){
$_SESSION["ErrorMessage"] = "Post title should be greater than 10 characters";
redirect_to("addnewpost.php");
} else {
//All is good insert into the database
$sql = "INSERT INTO posts(datetime,title,category,author,image,post)";
$sql .= "VALUES(:dateTime,:postTitle,:categoryName,:adminName,:imageName,:postDescription)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':dateTime',$DateTime);
$stmt->bindValue(':postTitle',$posttitle);
$stmt->bindValue(':categoryName',$Category);
$stmt->bindValue(':adminName',$admin);
$stmt->bindValue(':imageName',$image);
$stmt->bindValue(':postDescription',$posttext);
$Execute=$stmt->execute();
move_uploaded_file($_FILES["image"]["tmp_name"],$target);
if($Execute){
$_SESSION["SuccessMessage"]="Post with id : ".$conn->lastInsertId()." Added Successfully";
redirect_to("addnewpost.php");
} else {
$_SESSION["ErrorMessage"]="Something went wrong. Try again";
redirect_to("addnewpost.php");
}
}
}
?>
Here is a screengrab showing that the category fields are empty. I do have display errors enabled but none are showing up. Any thoughts appreciated...

Thank you Nigel and Felippe. I just took out the option value so it's just this instead...
<option><?php echo $CategoryName; ?></option>
That's made it all work perfectly. Been looking at this for hours as well.
Thank you both.

<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value="<?php echo $CategoryName; ?>"><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
This is more like it

Related

Comboboxes return null value in PHP

Hi I have five (05) comboboxes in the form that fetch values from database but while editing form all comboboxes return no value. I have to select values in the combobox all the time to update form.
Here is my code:
if(isset($_POST['submit']))
{
$fname=validate($_POST['fname']);
$mname=validate($_POST['mname']);
$lname=validate($_POST['lname']);
$gender=validate($_POST['gender']);
$contact=validate($_POST['contact']);
$proid=validate($_POST['proid']);
$distid=validate($_POST['districtid']);
$degid=validate($_POST['degreeid']);
$batchid=validate($_POST['batchid']);
$majorid=validate($_POST['majorid']);
$desg=validate($_POST['designation']);
$inst=validate($_POST['institute']);
$add=validate($_POST['address']);
$userid=$_SESSION['id'];
$img=validate($_POST['featured_img']);
$oldimg=validate($_POST['old']);
$tmp_name = $_FILES['featured_img']['tmp_name'];
$dest = "alumni_images/";
if($img=='') {
$img=$oldimg;
$sql = "UPDATE alumnidata SET firstname='$fname',middlename='$mname',
lastname='$lname',gender='$gender',
address='$add',province_id='$proid',
district_id='$distid',contact='$contact',
degree_id='$degid',batch_id='$batchid',
major_id='$majorid',job_title='$desg',
connected_to='$inst',avatar='$img'
WHERE user_id='$userid'";
if (mysqli_query($con, $sql)) {
move_uploaded_file($tmp_name,$dest.$img);
$msg="Data has been updated successfully";
} else {
$error= "<b>in updating record:</b><br/>" . mysqli_error($con);
}
} else {
$sql = "UPDATE alumnidata SET firstname='$fname',middlename='$mname',
lastname='$lname',gender='$gender',
address='$add',province_id='$proid',
district_id='$distid',contact='$contact',
degree_id='$degid',batch_id='$batchid',
major_id='$majorid',job_title='$desg',
connected_to='$inst',avatar='$img'
WHERE user_id='$userid'";
if (mysqli_query($con, $sql)) {
move_uploaded_file($tmp_name,$dest.$img);
$msg="Data has been updated successfully";
} else {
$error= "<b>in updating record:</b><br/>" . mysqli_error($con);
}
}
Here is my HTML code of one combobox and similar code is for other 04 comboboxes. I have to choose value every time for updating form because if i don't do this, comboboxes return empty value:
<select name="proid" class="form-control" id="provinceid" required="required">
<option value="<?php echo $row['province_id'];?>" disabled selected><?php echo $row['province_name'];?></option>
<?php
$query1="Select * from tblprovinces";
$result1 = mysqli_query($con,$query1);
if(mysqli_num_rows($result1)>0) {
while($row1= mysqli_fetch_assoc($result1)) {
?>
<option value="<?php echo $row1['province_id']; ?>"><?php echo $row1['province_name']; ?></option>
<?php
}
}
?>
</select>
Thanks for helping. My problem is solved. I renamed the primary key field name different.... Three tables had same field name

adding selected attribute to dropdownlist item if is in array

I have code table like this.
code
00
01
02
03
I'm adding this codes as array from dropdown list to assigned_code column in the user table.
assigned_code
00,02,03
When I want to edit the codes assigned to the user, I need to add selected attribute which codes are assigned previously in dropdown list. I'm stuck at this point. Can anyone show me the how to do this?
<?php
$assigned_code = array();
$sql = "select assigned_code from user where ID=1";
$rq = mysqli_query($conn, $sql);
$count = mysqli_num_rows($rq);
if ($count>0) {
while ($row = mysqli_fetch_array($rq)) {
$assigned_code=$row["$assigned_code"];
}
}
?>
<select name="u_codes[]" id="u_codes" class="selectpicker" multiple="multiple">
<?php
$sql = "select code,desc from codes";
$rq = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($rq)) {
$code = $row["code"];
$codeDesc = $row["desc"];
if ($assigned_code == $code) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
}
?>
</select>
try using array_push to items
array_push($assigned_code,$row["$assigned_code"]);
because every time you use $assigned_code=$row["$assigned_code"];
you erase the existing value inside $assigned_code
and debug it with var_dump() it will give you a clear information about the data and it's type.
$assigned_code = array();
$assigned_code=$row["$assigned_code"];
$expArr = explode(',',$assigned_code);
if (in_array($code,$expArr)) {
echo '<option value="'.$code.'" selected="selected">'.$codeDesc.'</option>';
} else {
echo '<option value="'.$code.'">'.$codeDesc.'</option>';
}
in_array perfectly worked for me.

How do i get record in a dropdown list based on a first drop down list in php ajax request

Php ajax request not working even though the onchange function seems to be working.
Initially the get_data.php was in a folder different from the parent folder. I moved it to the same folder but still not working.
//html select option
<select name="slct" id="slct1">
<option selected disabled>----Choose Class ----</option>
<?php
$query = "SELECT * FROM classes ";
//GET RESULT
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()){
?>
<option value="<?php echo $row['class_name']?>"><?php echo $row['class_name']?></option>
<?php
}
?>
<select name="slct" id="slct2" >
<option selected disabled>----Select Student----</option>
</select>
//ajax request
<script type="text/javascript">
$(document).ready(function(){
$('#slct1').on('change',function(){
var StudentID = $(this).val();
if(StudentID){
$.ajax({
type:'POST',
url:'get_data.php',
data:'class_name='+StudentID,
success:function(html){
$('#slct2').html(html);
}
});
}else{
$('#slct2').html('<option value="">Select Class First</option>');
}
});
});
</script>
//get_data.php
<?php
//Include the database configuration file
include '../config/dbconfig.php';
if(isset($_POST["class_name"])){
//Fetch all state data
$query = "SELECT * FROM students WHERE class = ".$_POST['class_name']." ORDER BY id ASC";
//Count total number of rows
$result = $pdo->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
$rowCount = $result->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select Student</option>';
while($row = $result->fetch()){
echo '<option value="'.$row['class'].'">'.$row['firstname']. $row['middlename'] . $row['lastname']. '</option>';
}
}else{
echo '<option value="">No Student Registered</option>';
}
}
?>
I want to get student records in the second select option when class is selected.
As mentioned in the comment - it looks like the issue might be dues to lack of quotes around the POST variable in the SQL query. This would not have been an issue had you used a prepared statement and bound the POST variable to a placeholder - the added benefit is of course greater protection from SQL injection.
<?php
if( isset( $_POST['class_name'] ) ){
include '../config/dbconfig.php';
$sql = 'select * from `students` where `class` = :classname order by id asc';
$args = array(
':classname' => $_POST['class_name']
);
$stmt=$pdo->prepare( $sql );
if( $stmt ){
$result=$stmt->execute( $args );
if( $result && $stmt->rowCount() > 0 ){
echo '<option selected hidden disabled>Select student';
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
printf('<option value='%s'>%s %s %s', $rs->class, $rs->firstname, $rs->middlename, $rs->lastname );
}
} else {
echo '<option selected hidden disabled>No student registered';
}
} else {
exit( '<option selected hidden disabled>error' );
}
}
?>

Error 500 malformed header from script. Bad header in PHP

I have a site thats works without any issues on wamp but once i host it in a bluehost account i get error 500 on both submit form and any ajax calls.
example of an error is
malformed header from script. Bad header=user_auth.php: fetch_cities.php
the user_auth.php thats the login script no need of posting it here.
Am using php 5.6 i did google and some of the solutions i found were like to check inside php.ini, no line showing magic_quotes_cpg=on or register_globals = on . Any pointers on what could be the issue is appreciated
fetch_cities.php
<?php
include('../../bin/initaccess.php');
$city = mysqli_real_escape_string($con, $_POST['city']);
$number = mysqli_real_escape_string($con, $_POST['number']);
if($number == 0){
echo "<option value=''>-- Select City --</option>";
$sql = "SELECT city_name FROM cities";
}else{
$sql = "SELECT city_name FROM cities WHERE city_name = '$city'";
}
$result = $db->query($sql);
while($row1 = mysqli_fetch_array($result)){
$city_name = $row1['city_name'];
?>
<option <?php if($city_name == $city){ echo "selected"; } ?> value='<?php echo $city_name; ?>'><?php echo $city_name; ?></option>
<?php
}
?>

Edit Using Dropdown - Codeigniter

I have these two table in my database:
tbl_province
id | id_prov | prov_name
and
tbl_district
id | id_dist | id_prov | dist_name
and
tbl_myhome
id | id_prov | id_dist | name | address
and I have this controller for edit & update:
public function edit()
{
$this->load->model('m_login');
$level = $this->session->userdata('level');
$data['menu'] = $this->m_login->get_menu_for_level($level);
$data['title'] = 'District Data';
$data['content'] = 'district/v_edit_dist';
$id = $this->uri->segment(3);
$this->db->where('id_dist',$id);
$q = $this->db->get('area_db');
if($q->num_rows()>0){
foreach($q->result() as $row){
$data['id'] = $row->id;
$data['id_dist'] = $id_dist;
$data['dist_name'] = $dist_name;
}
} else {
$data['id'] = '';
$data['id_prov'] ='';
$data['id_dist'] ='';
$data['dist_name'] ='';
}
$this->load->view('v_home',$data);
}
And this is my v_edit_dist source on Dropdown:
<?php
$q = $this->db->get('tbl_myhome');
foreach($q->result() as $row){
$distname = $row->dist_name;
?>
<select name="id_dist" id="id_dist" class="form-control">
<option selected="<?php echo $id_dist;?>"><?php echo $dist_name;?></option>
</select>
When I tried to edit my data per-row, all the data's in the dropdown menu showed up, all the district name just showing up, and the district name in the form was wrong, it's showing the first district id, but actually in the database the data is the fifth district id.
I just confused how to make the district name on the dropdown match with the one in the database, and not all the district names shows up and messing the css. Please help..helep...I'm desperate.
Thank you.
<select name="id_dist" id="id_dist" class="form-control">
<option value="<?php echo $id_dist;?>"><?php echo $dist_name;?></option>
</select>
///// In controller file
public function edit()
{
$this->load->model('m_login');
$level = $this->session->userdata('level');
$data['menu'] = $this->m_login->get_menu_for_level($level);
$data['title'] = 'District Data';
$data['content'] = 'district/v_edit_dist';
$id = $this->uri->segment(3);
$q = $this->db->get('tbl_district');
$district = array();
if($q->num_rows()>0){
foreach($q->result() as $row){
$district[]= $row;
}
}
$data['id_dist'] = $id;
$data['district']= $district;
$this->load->view('v_home',$data);
}
// in view file
<select name="id_dist" id="id_dist" class="form-control">
<?php
if(count($district)){
foreach($district as $item){
?>
<option value="<?php echo $item->id_dist; ?>" <?php if($item->id_dist==$id_dist) echo 'selected';?>><?php echo $item->dist_name;?></option>
<?php
}
}
?>
</select>
Use this code on your view page
<select name="id_dist" id="id_dist" class="form-control">
<?php
$q = $this->db->get('tbl_myhome');
$result = $q->result();
foreach($result as $row){
?>
<option value="<?php echo $row->id_dist;?>" <?php if($row->id_dist==$id_dist){ echo 'selected';} ?>><?php echo $row->dist_name;?></option>
<?php } ?>
</select>

Categories