<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character`";
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action ="handler.php" method="post">
<label for="character">SELECT A CHARACTER </label>
<select multiple name="character">
<?php while($character = mysqli_fetch_assoc($result1)){?>
<option value ="<?php echo $character['id'];?>"</option>
<?php echo $character['name'];?></option>
<?php }?>
<input type="submit" value="submit"/>
</select>
</form>
</body>
</html>
this is my index page above
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character` where id = ". $_POST ["character"];
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php while($character = mysqli_fetch_assoc($result1)){?>
<?php echo $character["name"];?><br>;
<?php echo $character["attack"];?><br> ;
<?php echo $character["defense"];?><br>;
<?php } ?>
</body>
</html>
alright here is my handler page the issue I am having is I can select multiple options in my html select on my index page but I am having a problem displaying when multiple characters are selected in my handler page. Does anyone know how to fix this specific issue? I also want the data to displayed in a table which I'm pretty sure I can figure out.
What You actually need is logical approach. You have to ask yourself a question "what You want", "what You need" and "how to do it".
So in Your case You want to compare something but You didn't actually say what exactly You need. So if You're new i can can help You that:
What You need for sure is webpage, where user can select character from a list. But what then? I don't know. You didn't specify so...:
1) Show user a select box to choose character. How to get them? Select from database. This is what You already have.
2) After user select character You need to send this data to the server. How to do it? Use <form> tag like:
<form method="post">
<select name="character">...option list...</select>
<input type="submit" value="Search">
</form>
3) Get data sent by Your form and use them to compare with... something You have.
<?php
if( isset( $_POST['character'] ) ){
// do something with this character
}
?>
4) Show user response like found or not found or something else. Pass this data into some div like:
<?php
$found = 'set this true OR false';
if( $found ){
$message = 'Found it!';
}else{
$message = 'Not_found!";
}
?>
Then in HTML write something like:
<div><?php echo isset( $message ) ? $message : ''; ?></div>
Thats it, rest is up to You. Any simple problem You will solve by searching in Google.
-------- Edit
First of all if You're using multiple select box, the name must be:
<select name="character[]" multiple>
Then Your $_POST['character'] is now an array. You can check its content by:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Use foreach:
$ids = []; // or $ids = array(); if php version lower than 5.4
foreach( $_POST['character'] as $v ){
$ids []= (int) $v;
}
$query = 'SELECT * FROM `character` where id IN ('. implode(',', $ids) .') ';
Related
I want to pass a select option value through hyperlink to the next page and for this I have this code:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<form name="search_form" role="form" method="GET" id="search_form" action="SearchResults.php">
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM attributes WHERE attributename='mushtype'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select id="mushtype" name="mushtype">
<option value="*" selected>Mushroom types</option>
<?php foreach($data as $row): ?>
<option value="<?php echo $row['idattributevalue']; ?>"><?php echo $row['attributevalueEN']; ?></option>
<?php endforeach; ?>
</select>
<?php
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Find Your Mushroom
</form>
</body>
</html>
For the default selected option I want to use (*) as value because if no option are selected, will stand as SELECT (all) FROM for my SQL query on the second page.
So, i tried to construct my hyperlink, but i don't know how to catch the selected option.
I tried to adapt from here
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['Movies'])) {
$selected = $_POST['Movies'];
echo 'You have chosen: ' . $selected;
} else {
echo 'Please select the value.';
}
}
?>
but I'm unable to do it.
Rigth now, my code inserting a value, but is without any control upon it.
Please help me to catch the selected option and insert it as value in my hyperlink. Thank you.
When you use <a>, you do not submit the inputs to the next page. Instead of
Find Your Mushroom
simply use
<input type="submit" value="Find Your Mushroom">
before closing the form.
Edit:
Depending on the <form method= you use ("get" or "post"), you will then either have $_GET['mushtype'] or $_POST['mushtype'] available in the next page. (Thanks to #ADyson!)
In my tests using method="get", the form inputs make their way to $_GET, but my uri parameters were not there. Using method="post" gave me both my uri parameters in $_GET and form details in $_POST, just in case you want to use both.
If you do not like the button style however, you can change it using CSS to look just like a regular hyperlink.
I have not worked with PHP for a long time. Recently, I have been assigned to a PHP project. I am in a like memory refreshing state now.
My problem is I have two PHP files.
test1.php
test2.php
test1.php
<html>
<body>
<form action="test2.php" method="post">
<?php
$description = "desc";
echo "<button name='.$description.' value='1'>description!</button>"
?>
</form>
</body>
</html>
test2.php
<?php
$answer = $_POST[$description]; //Undefined variable '$description'
echo $answer;
$sqlQuery = "SELECT * FROM StatsData WHERE code_name=$answer";
?>
Output
Warning: Undefined variable $description
Warning: Undefined array key
The problem is, I cannot pass the variable which is in the name tag to test2.php. How can I achieve my result?
I think your approach is not the best one, I would rather define a hidden field in test1.php, which hold the name of button, then in test2.php get it and display the button value
<html>
<body>
<form action="test2.php" method="post">
<input type="hidden" name="btnName" value="<?php echo $description; ?>"/>
<?php
$description = "desc";
echo "<button name='.$description.' value='1'>description!</button>"
?>
</form>
</body>
</html>
Then in test2.php
<?php
$answer = $_POST[$_POST["btnName"]];
echo $answer;
?>
I thought of adding a variable to the name tag and send it to another page and output the value. But, I am wrong. It was all about the value tag
test1.php
<html>
<body>
<form action="test2.php" method="post">
<?php
$description = "1";
echo "<button name='desc' value='$description'>description!</button>"
?>
</form>
</body>
</html>
test2.php
<?php
$answer = $_POST["desc"];
echo $answer;
$sqlQuery = "SELECT * FROM StatsData WHERE code_name=$answer";
?>
With the help of this community, I found out what was my mistake. I have confused between name tag and value tag. That was the reason.
My blog was posting originally, however, as you work on things, things break. Now I can't for the life of me figure out why nothing is happening! The categories post to the database just fine, but my posts refuse to. Heres what I have
<?php
include_once('header.php');
if(isset($_POST['title'], $_POST['contents'], $_POST['category'])){
$errors = array();
if(!empty(trim($_POST['title']))){
$title = trim($_POST['title']);
}else{
$errors[] = 'Please enter title';
}
if(!empty(trim($_POST['contents']))){
$contents = trim($_POST['contents']);
}else{
$errors[] = 'You need to supply the content';
}
if(!category_id_exists($_POST['category'])){
$errors[] = 'That category does not exist.';
}
if(strlen(trim($_POST['title']))>255){
$errors[] = 'The title cannot be longer than 255 characters.';
}
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
label { display: block;}
</style>
<title>Add a Post</title>
</head>
<body>
<h1> Add a Post </h1>
<?php
if(isset($errors) && !empty($errors)){
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<form action="" method="post">
<div>
<label for="title"> Title </label>
<input type="text" name="title" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>">
</div>
<div>
<label for="contents"> Contents </label>
<textarea name="contents" rows="15" cols="50"><?php if(isset($_POST['contents'])) echo $_POST['contents']; ?></textarea>
</div>
<div>
<label for="category"> Category </label>
<select name="category">
<?php
foreach(get_categories() as $category){
?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?> </option>
<?php
}
?>
</select>
</div>
<div>
<input type="submit" value="Add Post">
</div>
</form>
</body>
</html>
Inside the header.php file, I call an init.php connect to db file which also in itself, include_once all the functions for my blog (blog.php). The function that specifically is necessary is as follows...
function add_post($title, $contents, $category){
global $mysql_connect;
$title = mysqli_real_escape_string($mysql_connect, $title);
$contents = mysqli_real_escape_string($mysql_connect, $contents);
$category = (int)$category;
$result = mysqli_query($mysql_connect, "INSERT INTO posts SET cat_id = '$category', title = '$title', contents = '$contents', date_posted = NOW()");
}
I figured a fresh set of eyes could be really valuable for me right now. When I click add post, it brings me to a page titled http://localhost/blog/index.php?id=0. Therefore it's not only not registering to the database, but it's not using the categories either.
I hope I explained this okay! I've been at this for a week now.
Edit: I ran error checks and nothing posts, so I am not sure what's going on!
Edit2: Selecting categories I add, also work and list the way I want them to. Its just something happening when I go to click add post, nothing occurs. I'm assuming its in this area
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
As with any problem, it's always a needle in a haystack! I ran code through MYSQL workbench, and found out it was my setting to a foreign key that didn't need a relationship. It's all fixed now!
SQL Error Screenshot
I think the problem is with your database table posts.
One Case is:
You need to have an AUTO_INCREMENT field (id for example) so that the function mysqli_insert_id works perfectly. And in your case the solution would be to make the id column an AUTO_INCREMENT field.
Here is a quote:
The mysqli_insert_id() function returns the ID generated by a query on
a table with a column having the AUTO_INCREMENT attribute. If the last
query wasn't an INSERT or UPDATE statement or if the modified table
does not have a column with the AUTO_INCREMENT attribute, this
function will return zero.
I have an html page that loads list of hotels in a select tag from a MySQL table using PHP. The select tag is inside a form tag. Whenever I load the page, the option tags will load, but when I submit my form, the option tags never load anymore. My form's action attribute is empty, I am checking everything on the same page, but when I put another php page as action, it loads normally. Is there a way to make it load after submit while keeping my form's action empty?
Here is my code
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
$db->disconnect();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
If $_POST['search'] is set, you $db->disconnect(); so it can't run the query in your form.
Take the $db->disconnect(); out of your if() statement, and put it at the end of the file.
The issue is with the disconnect, when the page reload after submit your connection to mysql lost due to
$db->disconnect();
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
using select list with mysql created a list. I have a mysql data with c_code,Table center,and having data 1. id,2. name,3. code. i want to select name from mysql data after selecting name in data list want to show the code crosponding that name without using any submit button from select dropdown list, and the code shows in either label or in inputtext box.
Here is my full code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title
</head>
<body>
<form id="form1" name="form1" action="" , method="post" >
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name,code FROM center');
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
First, let's organize the code a bit...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn=mysqli_connect('localhost','root','');
$result=mysqli_query($conn,'SELECT id,name,code FROM center');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
Second, dynamically doing anything in HTML is impossible with PHP, PHP is a server-side script and can not post back data after user manipulations without refreshing the page.
You are looking for an $.ajax(); solution. I'd suggest looking into it on http://api.jquery.com/jQuery.ajax/
Good luck!
you should write select tag out of form
because this list will not populated until form submitting
Hope its this what you need. you do a select on the id and name for the dropdown menu. after you selected an element the form ll be submitted and a new sql query ll return you the code. there are several other ways to return the code, this is just one easy way
notice, i didnt use prepared statements! because i do not have the correct synatx in head right now... you should think about a general implementation of prepared statements.
<form id="form1" name="form1" action="" method="post" >
<div>
<label for="list">Center</label>
<select name="list" onchange="this.form.submit()">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name FROM center');
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[id]' $selected >$row[name]</option>";
}
?>
</select>
</div>
<div>
<?php
if (isset($_POST['list']))
{
$result = mysqli_query($conn, 'SELECT code FROM center WHERE id=' . $_POST['list']);
while ($row = mysqli_fetch_assoc($result))
{
echo $row['code'];
}
}
?>
</div>
</form>
Try to echo $row variables separately by concatenation.
So change this line
echo "<option value='$row[id]'>$row[name]</option>"
to
echo "<option value=". $row[id] .">".$row[name]."</option>"
or you can use escape character like this
echo "<option value={$row[id]}>{$row[name]}</option>"
I think now your select option would work.
If I understand you right, you're trying to do the same thing I was before I discovered this solution...
I was creating a dropdown for selecting how many results to show per page.
Total of 6 options, which I stored in an array...
$page_sizes = array(10, 25, 50, 100, 200, 500);
Next, I used a "foreach" to build the options list...and an if statement to show the option as selected ONLY if it matched the current page size (page size was determined earlier in the script using the $page_size variable)...
foreach($page_sizes as $pagesize_opt){
($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
Then, I inserted my options into my drop down...
$page_size_select = '<strong>Results Per Page </strong><select id="analytics_page_size_select">'.$pagesize_options.'</select>';
You could do the same using a "while" iterator. Just check to see if the array element matches your selected element.
OR, if you want to get fancy and use an associative array which selects the option by the key instead of by the value, you can use the "key()" function to get the key and test whether it matches your selected key...
http://php.net/manual/en/function.key.php
So the entire code looks like this...
$page_sizes = array(10, 25, 50, 100, 200, 500);
foreach($page_sizes as $pagesize_opt){($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
$page_size_select = 'Results Per Page '.$pagesize_options.'';