Button submit, gets the other buttons from the database - php

This is my code so far:
require_once 'functions.php';
// makes the connection to the server to get the state button names
$query = "SELECT state FROM state";
$result = $connection->query($query);
if ($result === false) {
// error mssg
echo "<p>Query fout.</p>";
}
// button of the state gets the buttons of the city
if (isset($_POST['state'])) $state = $_POST['state']; {
query = "SELECT city FROM city='$cityid'";
$result = $connection->query($query);
} if ($result === false) {
// geef nette foutmelding
echo "<p>Query fout.</p>";
}
<?php
//gives the result to Submit html
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."'>";
}
$result->free();
?>
</for
I would like to have a form submit button that gives a variable to PHP, depending on that variable, other buttons are created in the same form. So you can select a country and than you can select the cities in that country. I have the first button up and running. I thought I could just use the same submit button with the same variables. Because php would just rewrite the variables if there is a new input. But I think its not that simple, I don't know how to Google this question or that it is even something I should do with PHP instead of JavaScript/jQuery and just let the buttons hide and display and only use the last one to give an input with PHP.

you need to do the query result separately, so there should be two while statements
not the best way but here is one way i would do it:
require_once 'functions.php';
$query = "SELECT state FROM state";
if($query->num_rows > 0){
while($row= $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."' onclick="sendVal(this.value)" >";
}
}
<script type="text/javascript">
function sendVal(item) {
document.cookie="city=" + item + ";";
location.reload();
}
</script>
<?php
if(!is_null($_COOKIE['city'])){
$retrievedcities= "SELECT city FROM city WHERE city ='".$_COOKIE['city']."'";
$con->query($retrievedcities);
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='citybut' value='".$row['city']."'>";
}
unset($_COOKIE['city']);
}
?>

Related

Dropdown to read in and sort users with PHP

I am working on a project where I need to read in users (am using MySQL) and be able to sort 1. Men/Women 2. Salary (eg. 30k+, 50k+, 100k+...)
I've tried setting up a select dropdown but for some reason it's showing only the men, even if I select women.
<form action="#" method="post">
<select name="Gender">
<option value=''>Select Gender</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
if(isset($_POST['submit']) && $_POST['submit'] = "Men"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
elseif (isset($_POST['submit']) && $_POST['submit'] = "Women"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
else {
print("-");
}
You've assigned the values in the ifs instead of comparing against them. Also, you've used the wrong input to compare against. $_POST['submit'] will always contain the value Get Selected Values.
if (isset($_POST['submit']) && $_POST['Gender'] === "Men") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} elseif (isset($_POST['submit']) && $_POST['Gender'] === "Women") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} else {
print("-");
}
Here's the code a little more simplified and less redundant. And under the assumption that you're using PHPs PDO.
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
$gender = $_POST['Gender'] ?? null; // your old $selected_val variable
if (!$gender) {
// do something to abort the execution and display an error message.
// for now, we're killing it.
print '-';
exit;
}
/** #var PDO $dbConnection */
$dbConnection = create_Conn();
$sql = 'SELECT * FROM users WHERE kon = :gender';
$stmt = $dbConnection->prepare($sql);
$stmt->bindParam('gender', $gender);
$stmt->execute();
foreach ($stmt->fetchAll() as $user) {
if (isset($_SESSION['anvnamn'])) {
// Prints user data
} else {
// Prints user data but emails
}
}
}
As Dan has provided a grand answer prior to mine, this is now just a tack on for something to review.
If you look at your form you have two elements.
On Submission, your script will see..
Gender - $_POST['Gender'] will either be '', 'Men', or 'Women'
Submit - $_POST['submit'] will either be null or the value "Get Selected Values".
It can only be null if the php file is called by something else.
You can see this by using the command print_r($_POST) in your code just before your first if(). This allows you to test and check what is actually being posted during debugging.
So to see if the form is posted you could blanket your code with an outer check for the submit and then check the state of Gender.
The following has the corrections to your IF()s and some suggestions to also tidy up the code a little bit.
<?php
// Process the form data using Ternary operators
// Test ? True Condition : False Condition
$form_submitted = isset($_POST['submit'])? $_POST['submit']:FALSE;
$gender = isset($_POST['Gender'])? $_POST['Gender']:FALSE;
if($form_submitted){
if($gender == 'Men') {
// Stuff here
}
else if($gender == 'Women') {
// Stuff here
}
else {
print("-");
}
} else {
// Optional: Case where the form wasn't submitted if other code is present.
}
You could also consider using the switch / case structure. I'll leave that to you to look up.

trying to use combobox populated from mysql to send the $id to a second page to be used in a query

Trying to use ComboBox populated from mysql to send the $id to a second page to be used in a query to populate data.
Here is my code sitting in the bootsrap nav bar on page 1
<form class="navbar-form navbar-left" action='customerpage.php' method='post'>
<div class="form-group">
<select type="submit" id="navbarcustomer" class="form-control" name='customerid' placeholder="Customer Lookup">
<option>Customer Lookup</option>
<?php
require ('dbconnect.php');
$result = $con->query("select id, lastname, firstname from customer");
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['lastname'];
$firstname = $row['firstname'];
echo '<option value="/customerpage.php?id='.$id.'">'.$name.','.$firstname.'</option>';
}
echo "</select>";
mysqli_close($con);
?>
</div>
</form>
here is my code on page to that needs to receive the $id variable to be used in the query
<?php
$id = $_GET['custid'];
echo $id;
require ('dbconnect.php');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE id=' . $id . '");
//$result = mysqli_query($con,"SELECT * FROM customer WHERE id=$id");
while($row = mysqli_fetch_array($result)) {
echo $row['firstname'];
echo "<br>";
}
?>
Please help the name of page 2 is /customerpage.php Thank you.
It looks like you've set it up so that when you click the dropdown, it will automatically go to the customers page. We will need just a little bit of JavaScript for that.
Place this below your closing </form> tag, but preferably right before you closing </body> tag document.
<script>
var navbarcustomer = document.getElementById('navbarcustomer');
navbarcustomer.addEventListener('change', function (e) {
window.location = this.value;
});
</script>
If you're using jQuery, you can OPTIONALLY use this in your <script> tags instead of the code above:
$('#navbarcustomer').on('change', function () {
window.location = $(this).val();
});
Next, you need to make sure your GET vars match what you're sending it. Change $_GET variable to look like this, as you are providing id= in the query string (and not custid=):
$id = $_GET['id'];
Edit:
There are a few more things that need to be addressed. Also in the customerpage.php, your query is little broken. You can use something like to fetch your records, it's a little bit cleaner:
$id = (int) $id; // cast to integer to prevent SQL injection.
$result = $con->query("SELECT * FROM customer WHERE id = $id");
// there is only going to be 1 record so we don't need the while loop.
$row = $result->fetch_assoc();
echo $row['firstname'];
echo $row['lastname'];

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

double click required to insert into database

this might be a really simple solution but I really can't figure it out. if i insert into my database I have to press the insert button twice for it to work.. My guess is that it has to do with my using of 2 forms in one file or just because I did it all in one file. please help me.
thanks
code:
<?php
/*require "link.php";*/
?>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="css.css">--> <!-- verwijzing naar je css -->
<!--<script type="text/javascript" src="js.js"></script>-->
</head>
<header>
</header>
<article>
<div id="cards">
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$array = array();
$IDarray = array();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr id='".$rows['ID']."'><td>".$rows['Question']."</td><td><input type='text' name='Answer[]' id='V".$rows['ID']."'></input></td></tr>";
$array[] = $rows["Answer"];
$IDarray[] = $rows["ID"];
}
echo "</table><input type='submit' name='submit'></input></form>";
$i = 0;
$count = sizeof($IDarray);
if(!empty($_POST['Answer']))
{
foreach($_POST['Answer'] as $answer)
{
if (isset($_POST['Answer'])) {
if ($answer == $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='green'; document.getElementById('V".$IDarray[$i]."').value='".$array[$i]."'</script>";
}
elseif ($answer !== $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='red'; document.getElementById('V".$IDarray[$i]."').value='".$answer."'</script>";
$count = $count-1;
}
$i ++;
}
}echo $count." van de ".sizeof($IDarray)." goed";
if ($count == sizeof($IDarray))
{
header('Location: http://localhost:1336/php3/');
}
}
echo "</br></br>insert";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
echo "<tr><td>vraag</td><td><input type='text' name='vraag'></input></td><td>antwoord</td><td><input type='text' name='antwoord'></input></td></tr>";
echo "</table><input type='submit' name='submitinsert' value='insert'></input></form>";
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
?>
</div>
</article>
<footer>
</footer>
</html>
The problem is you're processing the form submission in the same script as the one that generates the form. Couple that to the fact that you firsT query the DB, generate a form with what you've already stored, and then add whatever data the user may have posted, you'll never see the data you've added show up the first time 'round you submit the form.
Either move the insert queries to the top (before generating the form), or separate concerns
Let me show you what I mean:
//don't OR DIE
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{//build form here
}
/*
CODE HERE
*/
if ($_POST['vraag'] != "") {
//insert here, after form is generated
}
So the data you query cannot, yet, contain the submitted form data.
There are some other issues with the code, though, like or die: don't do that. Be consistent with your coding style (allman brackets + K&R in the same script is messy). Properly indent your code and this:
if ($_POST['vraag'] != "") {
}
should be:
if (isset($_POST['vraag'])) {
}
You're comparing a key of an array that may not exist to an empty string, whereas you should check if that array key exists. Use isset.
I could go on a bit, but I'll leave it at that for now. Just one more thing: again -> separrate concerns! The presentation layer (the output: HTML and such) should not contain DB connection stuff. That should be done elsewhere.
Process your form either asynchronously (as whatever is submitted gets added to the table that is already there) using AJAX, or at least, use a separate script. Having 1 script doing all the work will soon leave you crying over a mess of spaghetti code
Its not submitting twice, actually its not loading the data after insertion,
Try adding
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
echo "are you sure?";
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
before
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or
die(mysqli_error($link));
this will select your records after the current record is saved.

php retain an array checkbox

I'm a complete noob but I have searched everywhere and can't find a solution.
What I have is an array of courses that I pull from my database (e.g.:
maths, art, science). These can change so I must add new courses all the time.
When a user ticks 2 of 3 courses (for example) but fails to add his username, then after the validation I want those 2 checkboxes to keep their old tick, so he must refill only his username in order to proceed.
What I get are all the checkboxes ticked :{
I'm so confused.
<?PHP
$check="unchecked";
?>
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_POST['cid'] as $cid ) {
$check="checked";
}
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>
You have to set your $checked variable independently for each checkbox.
$checkedBoxes = array();
foreach($cid as $id) {
$checkedBoxes[$id] = "checked='false'";
}
foreach ($_POST['cid'] as $cid) {
$checkedBoxes[$cid] = "checked='true'";
}
Then in your loop that outputs the checkboxes, print the corresponding $checked value.
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' {$checkedBoxes[$cid]}>"; // here are the courses(checkboxes)
}
Is this what you want?
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$cid_array = $_POST['cid'];
/*foreach ($_POST['cid'] as $cid ) {
$check="checked";
}*/
}
?>
<?PHP
$course_data = "SELECT * FROM course ORDER BY cname";
$get_course = mysql_query($course_data) or die (mysql_error());
while ($db_field = mysql_fetch_assoc($get_course)){
$cname= $db_field['cname'] ;//course name
$cid= $db_field['cid'] ;// course id
if(is_array($cid_array))
{
if(in_array($cid, $cid_array))
{
$check="checked='checked'";
}
else
{
$check="";
}
}
else//it is not array because nothing was checked
{
if($cid == $cid_array)
{
$check="checked='checked'";
}
else
{
$check="";
}
}
print"<BR>".
"<FONT COLOR='blue' SIZE='4'><B>$cname</B></FONT>".
"<input type='checkbox' name='cid[]' value='$cid' $check>"; // here are the courses(checkboxes)
}
?>

Categories