Ajax response option value not inserted to database - php

I am trying to make a category and sub category option in which sub-category will be selected according to the category . I am using ajax for this . In the php script I am using file() to read the sub categories . Now although sub-categories are appearing in my site , its value is not inserted into the database . M confused . Here are the codes :
$arr = file(SUB_CAT_DIR.$val);
echo '<select name="ad_sub_category">';
foreach($arr as $line)
{
echo '<option value="'.$line.'">'.$line.'</option>';
}
echo "</select>";
And php script to insert into database :
$sql = "
INSERT INTO
tbl_classified
SET
classified_id = '$id',
classified_category = '$info[ad_category]',
classified_sub_category = '$info[ad_sub_category]'

Is this MySQL? You havent said..
Normally I'd have expected to see
Insert into mytable (field1,field2,field) values('$field1','$field2','$field3')
Have you tried getting the value of $sql as a string, echo it to screen, and then run it direct through the command line, to check errors? or to confirm your SQL statement is being formed? Have you run the mysql_error function in case its complaining its a dup or something (see http://us3.php.net/mysql_error)

Related

PHP Select tags problems

I just started learning some PHP and SQL for my uni. I got everything figured out somehow but there have been a few problems. So what I'm doing is getting the values of a 'select' dropdown dynamically from the Database.
$sql = "SELECT catDesc, catID from Categories";
$queryResult = $dbConn->query($sql);
echo '<select name="eventcat" size="1" class="dropdownstyle" id="catevent" required/>';
echo '<option value="choose">Event Category</option>';
while($row=mysqli_fetch_array($queryResult)){
$xx = $row['catDesc'];
$id = $row['catID'];
echo '<option value="' . $id . '">' . $xx . '</option>';
}
So this above piece of code works. However. After the user submits the form. It redirects to a new page. "admin-process.php". I want this page to somehow get the value of the variable "$xx". I know how to get the value by using this method:-
$id = isset($_REQUEST['eventcat']) ? $_REQUEST['eventcat'] : null;
However, this displays the id of the option. Not the main thing that I need. The id and the value differ here. So in short. How do I get the name of the option tag?
How do I get the name of the option tag.
You don't. At least not directly. The only value posted as part of the form is the selected value from that element. In this case your catID value.
That value should uniquely identify the record which was selected. (If it doesn't, that's a different problem.) With that value you can then query the database to get the rest of the information from the uniquely identified record. It may contain one more field, several more fields, joins with other tables, etc. Doesn't really matter what it contains, as long as you can uniquely identify it based on that ID.
So on your next page (admin-process.php) you'd read the posted catID value and use it in a query to your Categories table. That query should return one record, from which you'd display the additional data.

php mysql show result one after another

I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck

dropdown from MySQL database

Having solved the populating the dropdown from the array, the next phase of my project is pulling data from a database to allow users to put limits on the data they want to see.
Again, I'm having trouble populating the dropdown. This time however, the problem seems to be that when I put the HTML interspersed with the PHP, the whole thing stops- the form loads, but nothing goes into the drop down.
Here's the code.
//Step One: Query the DB, and get a list of monthly reports
$sql = "SELECT Report_Text, Report_Date FROM ADM_8_Reports_List";
$result = $conn->query($sql);
//print_r ($result);
$reports_in_db = mysqli_fetch_all($result,MYSQLI_ASSOC);
if (sizeof($reports_in_db) > 0)
{
print_r ($reports_in_db);
echo "\n";
//Now, like the front page, create a form and populate it.
?>
Choose a Monthly Report <select name = "monthly_report">
<?php
foreach($reports_in_db as $row)
{
echo 'option value"' . $row ["Report_Date"] . '">' . $$row ["Report_Date"] . " " . $row ["Report_Text"] . '</option>';
}
}
else
{
echo "I'm sorry, there's no data here. Please start again\n";
} ?>
</select>
<input type="submit" name="monthly report" value="Retrieve Report"">
the output
what it looks like is happening is that the code is freezing where I'm interpolating the HTML and PHP, and actually creating the dropdown.
basically on the previous page, the user can choose one of 4 things to do. On this page, there's an if statement based on $_POST from the previous page. Depending on the choice, the databased will be polled to get, in this case, a list of all the monthly reports. I've copied exactly the structure of what I did on the first page (where I was going from an associative array I hard-defined). I can't figure out what's wrong with the declaration of the dropdown, but that's where the thing's .. well stopping.
I am really annoyed by this.
I forgot '<'when declaring the option. And didn't see it until I posted the question here.
Sorry.

set variable as first option in array php mysql

I have a select box being filled in with a mysql query, it functions fine and is selectable. Data changes and works fine.
It currently sorts based on the branch_id column and what I want is the session variable of $branch_id to be the first option of the select box. This is based on the branch selected from a previous page.
This is where I am stuck.
Here is some sample code of the branch dropdown.
This selection then changes a list of users that appears in an options box below this code. It all functions fine, I just need to refine it so the currently selected branch(from a prev page) is the first in the branch dropdown.
If anyone can help I'd really appreciate it.
//get list of allowed Branchs
$AllowBranch = "SELECT branch_id FROM access WHERE userid IN (SELECT id FROM user WHERE username = '{$_SESSION['user']}') ORDER BY branch_id ASC";
$getAllowBranch = mysql_query($AllowBranch);
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<OPTION VALUE = '{$getAllowBranchRow['branch_id']}' "; if($NeedBranch == $getAllowBranchRow['branch_id']) { echo "selected"; } echo "> ".ucwords(strtolower($Namerow['name']));
}
echo "</SELECT>";
Check the source code to see if the selected attribute is put in the right option tag. Also, you forgot to close every <option> tag with a </option>, not sure, but this could also be the problem.
First of all, you have missing tag <select name="<your field name>"> before while loop.
Then you have missing closing tag </option> too. You cannot solve your problem, if you have HTML broken.
So, it should looks like this:
echo '<select name="<your field name>">';
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<option value='" . $getAllowBranchRow['branch_id'] . "'" . $NeedBranch == $getAllowBranchRow['branch_id'] ? " selected" : "" . ">" . ucwords(strtolower($Namerow['name'])) . "</option>";
}
echo "</select>";
What I have done?
Firstly, I fixed your missing HTML tags. Then I just simply used ternary operator to check if branch_id equals to $NeedBrach and if yes, add following string selected and if not, add nothing.
Don't forget to replace <your field name> with your expect select name.
Important final thoughts!
I have to remind using mysql_* is deprecated, you should use mysqli_* or PDO instead with prepared statements.

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

Categories