Keep getting Notice: Undefined index: whatever I do - php

I am trying to fill a table in my database from a drop down menu which I populated from another table from my database. The problem is that whenever I submit my query, it gives me the same error "Notice: Undefined index:" and won't fill the table. I am new to coding, so please be gentle.
This is the part for populating the drop down menu
<?php
#mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("motocikli") or die(mysql_error());
$query = "SELECT kategorija_ime FROM kategorija";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="kateg">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['kategorija_ime']."'>'".$row['kategorija_ime']."'</option>";
}
?>
</select>
<form action="insert.php" method="post">
<input type="submit">
</form>
And this is the insert.php
<?php
$dsn = 'mysql:dbname=motocikli;host=127.0.0.1';
$user = 'root';
$password = '';
$pdo = new \PDO($dsn, $user, $password);
function unesiPoruku($kateg)
{
global $pdo;
$upit = $pdo->prepare("INSERT INTO test (kateg) VALUES (:kateg)");
$upit->bindParam('kateg',$kateg);
$upit->execute();
}
$kateg = $_REQUEST['kateg'];
unesiPoruku($kateg);
?>
The error is showing for $kateg = $_REQUEST['kateg'];, the 'kateg' tag.

Your select box needs to be inside the form so that the value is posted properly to the server
ie.
<form action="insert.php" method="post">
<select name="kateg">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['kategorija_ime']."'>'".$row['kategorija_ime']."'</option>";
}
?>
</select>
<input type="submit">
</form>

Related

PHP option value based on database table

My problem now:
once I echo the value from the database its woking good. but when I submit the form I got an empty value of the selected option.
Can any one help. I tried to used {} in he value code but it did not work.
What I want :
Set the the value of the selected option as it is on the database to insert it into another table.
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="" selected>--select-- </option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['centerName'].'">'.$row['centerName'].'</option>';
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
Try this
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="0" selected>--select--</option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$name = $row['centerName'];
echo "<option value='$name'> $name </option>";
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
</select>
You will have to "expand" your select query to include the ID of the row, and then instead of $row['centerName'] use $row['id'] (or what your ID column is named) in the value argument of the option element, and not the 'centerName'. If I understood correctly what you want, this should be it.
Edit: And do switch to mysqli_, mysql_ has been deprecated.
try to write like this:
echo '<option value="',$row["centerName"],'">',$row["centerName"],'</option>';
Warning:
Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead.
Solution
I recreated your issue and enhanced your code using mysqli extensions, and it's working fine. Take a look at the following code,
<?php
if(isset($_POST['submit'])){
// display submitted option
echo $_POST['CenterTO'];
}
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbName = "stackoverflow";
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $dbName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Execute query
$result_set = $connection->query("SELECT centerName FROM jeCenter");
?>
<form action="form_page.php" method="POST">
<select name="CenterTO">
<option value="" selected>--select-- </option>
<?php
// Check if number of rows is greater than zero or not
if($result_set->num_rows > 0){
// Loop through each record
while($row = $result_set->fetch_assoc()){
?>
<option value="<?php echo $row['centerName']; ?>"><?php echo $row['centerName']; ?></option>
<?php
}
}else{
?>
<option value="none">No data</option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Close connection
$connection->close();
?>

Fill drop down list on page load php

I have two input text fields where user has to specify the begin and end of the fly.
<input type="text" name="start" placeholder="Start destination">
<input type="text" name="end" placeholder="End destination">
I would like to change that and give user to chose start and end destination from database.
<select>
<option value="$id">$name</option>
</select>
I know how to get done if i read database and input values manually, but i know its posible if page loads and execute my SELECT QUERY.
So i have to create dropdown list and fill that with a values from database.
This dropdown list has to be filled when the page load.
Some idea for this ???
I am working with php.
Thank you in advance !!
EDIT : I get done this only with php.
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "flights";
$conn = mysql_connect("$db_host","$db_username","$db_password") or die ("no conn");
#mysql_select_db("$db_name") or die ("no database");
if ($conn = true) {
// echo "";
}
//cyrilic
$sql = "SET NAMES 'utf8'";
mysql_query($sql);
//query for end
$sql="SELECT Distinct end from flights_table;";
$result=mysql_query($sql);
echo "<select name=\"city\">";
echo "<option>end destination</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['end']."'>".$row['end']." </option>";
}
echo "</select>";
?>
This php fires when page loads. Those select options i have putted in a form, and when form is submited, it fires php itself. I am getting selected options this way :
$startfly=$_POST['end'];
I am doing this for starting the flight :)
Thank you guys !
Try this :
At the top of page include your database connection file :
<?php
require "connection.php";
?>
Then :
<?php
$selectStart = "Start : <select name='start'>";
$selectEnd = "End : <select name='end'>";
$query = mysql_query("SELECT * FROM someTable ORDER BY dateField ASC");
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$selectStart .= "<option value='".$row['startItem']."'>".$row['startItemName']."</option>";
$selectEnd .= "<option value='".$row['endItem']."'>".$row['endItemName']."</option>";
}
}
$selectStart = "</select>";
$selectEnd = "</select>";
?>
In your HTML :
<form action='destinationPage.php' method='post'>
<?php
echo $selectStart;
echo $selectEnd;
?>
<input type='submit' value='Submit' />
</form>

Option list which can retrieve from and post to database

can anybody post an code for option list which can retrieve data dynamically from database, and once user selects from option list a record, that record must post it ($_POST) to database.. !!
ive tried this, it retrieves records from db, but not posting it :
<?php
require_once "db.php";
if (isset($_POST['a_id']) {
$a = $_POST ['a_id'];
$sql = "INSERT INTO projektet
VALUES ('$a')";
mysql_query($sql);
}
HERE IS THE PART SEEMS NOT WORKING :
<form method="post">
<select name="a_id">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('naho',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `arqitekti`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
<?php }
?>
</select>
<input type="submit" value="submit"/>
</form>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
This line looks strange... Shouldn't it be:
<option value="<?php echo $row[a_id]; ?>"><?php echo $row["a_emri"];?></option>
I think that your code is POSTing, but it wasn't getting any value because of the value declaration on the options of the select. After that change it should work.
PS: If your POST code isn't in the same page as your HTML, it's <form method="POST" action="YOUR_PAGE">, not only <form method="POST">.

Deleting Multiple Records using Checkboxes in PHP

I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>

select items from mysql

making a simple movie review site to practice PHP. on one page ( a form) i write a title and review and submit, it then adds the info to mysql. i'm trying to create a page where i can delete reviews i've written. i'm going about this by returning all titles into a form tag, where i can select on and then submit that form to a process page and delete the item.
having issues with the WHILE statement and SQL statement.
$conn = mysql_connect($host, $user, $password)
or die("couldn't make connection");
mysql_select_db('cms', $conn)
or die("couldn't select database");
$sql = "SELECT * FROM frontPage";
$sql_result = mysql_query($sql, $conn)
or die("couldn't execute query");
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
}
?>
<form method="post" action="deleteReview_process.php">
<select name="title">
<option><?php echo $movieTitle; ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
</form>
Try this, the fixes include closing your option tag, and including the option tag inside the MySQL loop so the option tag gets outputted each time there is a new item.
<?
$conn = mysql_connect($host, $user, $password)
or die("couldn't make connection");
mysql_select_db('cms', $conn)
or die("couldn't select database");
$sql = "SELECT * FROM frontPage";
$sql_result = mysql_query($sql, $conn)
or die("couldn't execute query");
?>
<form method="post" action="deleteReview_process.php">
<select name="title">
<?
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?
}
?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
</form>
Well for one thing, you're overwriting $movieTitle each time your loop repeats...don't you want to display all movie titles in your select list?
If you want to display all the movie titles, you need to read the results in and store them all. Currently you are overwriting $movieTitle every time you pull a record from your result. Try something like this:
$titles = array();
while($row = mysql_fetch_array($sql_result)) {
$titles[] = $row['title'];
}
//...
<select name="title">
<option><?php echo implode("</option>\n<option>",$titles); ?></option>
</select>

Categories