php form checkbox search - php

I have created this php code for a search in a mysql database. However, I have problems with the checkboxes part. Without the checkbox part it works fine, but with it says "no data found". The part for the checkboxes is called tarif-typ.
`
<?php
include "db_connect.inc.php";
$sql = "SELECT * FROM praemien";
$sql .= " where kanton like '" . $_POST["kanton"] . "' and franchise = ". $_POST["franchise"] ." and ";
switch($_POST["unfall"])
{ case 1:
$sql .="unfalleinschluss like 'OHN-UNF'";
break;
case 2:
$sql .="unfalleinschluss like 'MIT-UNF'";
}
$sql .=" and tarif-typ like '" . $_POST["tb"] . "' ";
$sql .= " order by praemie";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num==0) echo "Keine Datensätze gefunden";
while ($dsatz = mysqli_fetch_assoc($res))
echo $dsatz["versicherungsnamen"] . ", "
.$dsatz["kanton"] . ", "
.$dsatz["tarif-typ"] . ", "
.$dsatz["unfalleinschluss"] . ","
. $dsatz["praemie"] . "<br />";
mysqli_close($con);
?>
</body>
`
and here is my html form
`
<html>
<body>
<form action ="db_eingabe.php" method="post">
<p><input name="kanton" /> Kanton</p>
<p><input name="franchise" /> Franchise</p>
<p><input type="radio" name="unfall" value="1" checked="checked" />Unfall nein<br>
<input type="radio" name="unfall" value="2" />Unfall ja</p>
<br><p>
<b>Tarif</b>
</p>
<p><input type="checkbox" name="tb1" value="TAR-BASE" checked="checked" />Grund</p>
<p><input type="checkbox" name="tb2" value="TAR-HMO" />HMO</p>
<p><input type="checkbox" name="tb3" value="TAR-HAM" />HAM</p>
<p><input type="checkbox" name="tb4" value="TAR-DIV" />andere</p>
<p><input type="submit" />
<input type ="reset" /></p>
</form>
</body>
</html>
`

starting another post to keep things clean...
your PHP code:
<?php
include "db_connect.inc.php";
$sql = "
SELECT
*
FROM
`praemien`
WHERE
`kanton` LIKE '" . $_POST["kanton"] . "'
AND `franchise` = '". $_POST["franchise"] ."'
AND `unfalleinschluss` LIKE '" . $_POST["unfall"] . "'";
$tbs = array();
foreach( array( 'tb1', 'tb2', 'tb3', 'tb4' ) as $tb_key )
{
if ( empty( $_POST[$tb_key] ) ) continue;
$tbs[] = "`tarif-typ` LIKE '" . $_POST[$tb_key] . "'";
}
if ( !empty( $tbs ) )
{
$sql .= ' AND ( ' . implode( ' OR ', $tbs ) . ' )';
}
$sql .= " ORDER BY praemie";
echo $sql;
$res = mysqli_query($con, $sql) or die( mysql_error() );
$num = mysqli_num_rows($res);
if ($num==0) echo "Keine Datensätze gefunden";
while ($dsatz = mysqli_fetch_assoc($res)) {
echo $dsatz["versicherungsnamen"] . ", "
.$dsatz["kanton"] . ", "
.$dsatz["tarif-typ"] . ", "
.$dsatz["unfalleinschluss"] . ","
. $dsatz["praemie"] . "<br />";
}
mysqli_close($con);
?>
and your HTML code:
<html>
<body>
<form action ="db_eingabe.php" method="post">
<p><input name="kanton" /> Kanton</p>
<p><input name="franchise" /> Franchise</p>
<p><input type="radio" name="unfall" value="OHN-UNF" checked="checked" />Unfall nein<br>
<input type="radio" name="unfall" value="MIT-UNF" />Unfall ja</p>
<p>
<b>Tarif</b>
</p>
<p><input type="checkbox" name="tb1" value="TAR-BASE" checked="checked" />Grund</p>
<p><input type="checkbox" name="tb2" value="TAR-HMO" />HMO</p>
<p><input type="checkbox" name="tb3" value="TAR-HAM" />HAM</p>
<p><input type="checkbox" name="tb4" value="TAR-DIV" />andere</p>
<p><input type="submit" />
<input type ="reset" /></p>
</form>
</body>
</html>
NOTES: fixed franchise = '". $_POST["franchise"] ."' -- it did not have single quotes
changed the unfall radio group to have specific values to avoid the switch you had
lastly, if the tarif-typ and unfalleinschluss columns only contain specific strings you have shown, you do not need LIKE you can use '=', however, if you want to find the strings IN the values, i suggest LIKE '%search_string%' with the % wildcards.

I think your checkboxes should be radios with all the same name (tb) because there is no field named "tb" submitted in your form and that is the reason why your query fails.
<p><input type="radio" name="tb" value="TAR-BASE" checked="checked" />Grund</p>
<p><input type="radio" name="tb" value="TAR-HMO" />HMO</p>
<p><input type="radio" name="tb" value="TAR-HAM" />HAM</p>
<p><input type="radio" name="tb" value="TAR-DIV" />andere</p>

Related

Save questions answer to mysql with post method

Every question have 3 answers with the score of 0, 1, or 2 assigned in the database.
How can i save each answer with the question id and answer id with the name and the email?
It's about 50 questions in the questions row in the database that is displaying with this script:
<?php
include "config.php";
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Testar uppkoppling:
if (mysqli_connect_errno()){
// Databaskoppling error
exit("Couldn't connect to the database: ".mysqli_connect_error());
}
$result = mysqli_query($db,"SELECT * FROM que");
echo '<form action="taemot.php" method="post" id="MyForm">';
while($row = mysqli_fetch_array($result)) {
echo '' . $row['que_question'] . '
<input type="radio" name="' . $row['que_answer0'] . '" value="' . $row['que_answer0'] . '">
<input type="radio" name="' . $row['que_answer1'] . '" value="' . $row['que_answer1'] . '">
<input type="radio" name="' . $row['que_answer2'] . '" value="' . $row['que_answer2'] . '"><br>';
}
echo ' <input type="text" name="name" value="Namn"><br>
<input type="text" name = "email" value="Epostadress"><br>
<input type="submit" value="Submit"> </form>';
?>
taemot.php
<?
$name=$_POST['name'];
$email=$_POST['email'];
mysql_connect("XXXX", "XXXX", "XXXX")
or die(mysql_error()); mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO `data` VALUES ('$name', '$email')");
Print "Your information has been successfully added to the database."; ?>
Try have a input name as Array
// Assign $i to define which question number is on
<input type="radio" name="ans[$i]" value="'. $row['que_answer0'] .'">
<input type="radio" name="ans[$i]" value="'. $row['que_answer1'] .'">
<input type="radio" name="ans[$i]" value="'. $row['que_answer2'] .'">
$i++;
for taemont.php
$aryAns = $_POST['ans'];
foreach( $aryAns AS $key => $value ) { //$key is the question number, $value is the question answers
mysql_query("INSERT INTO data ....");
}
With this solutions $key row in database posts the value $i instead of question id?
How can this solution work with multiple questions, since there is about 50 questions when:
echo '' . $row['que_question'] . '
Right now only 1 value is clickable of 50 questions.
See this image to understand: http://s29.postimg.org/d4llvjajr/questions.jpg
$result = mysqli_query($db,"SELECT * FROM que");
echo '<form action="taemot.php" method="post" id="MyForm">';
while($row = mysqli_fetch_array($result)) {
echo '' . $row['que_question'] . '
<input type="radio" name="ans[$i]" value="'. $row['que_answer0'] .'">
<input type="radio" name="ans[$i]" value="'. $row['que_answer1'] .'">
<input type="radio" name="ans[$i]" value="'. $row['que_answer2'] .'">
';$i++;
}
echo ' <input type="text" name="name" value="Namn"><br>
<input type="text" name = "email" value="Epostadress"><br>
<input type="submit" value="Submit"> </form>';
taemot.php:
$aryAns = $_POST['ans'];
foreach( $aryAns AS $key => $value ) { //$key is the question number, $value is the question answers
mysql_query("INSERT INTO `data` VALUES ('$name', '$email', '$key', '$value')");
}
Print "Your information has been successfully added to the database."; ?>

Display different row of a database upon clicking a button

I have a database of mosques with the following fields: mosque_id, mosque_name, prefecture, address, postal_code, website, email1, phone1 . What I want to do is to display the information of the first mosque (mosque_id=1) in a form and when I click "Next", the information of the second mosque (mosque_id=2) will be displayed.
So far, I've been able to use mosque_id to select an entire row and display the information, but I've been struggling to find a way to switch to the next one. I'm very new to PHP and MYSQL, any help would be appreciated.
<?
$mosque_id = 1;
$result = mysql_query("SELECT * FROM Mosque WHERE mosque_id='$mosque_id'");
$row = mysql_fetch_assoc($result);
?>
<form action="insert.php" method="post">
Mosque Name: <?php print('<input type="text" name="firstname" value="' . $row['mosque_name'] . '"/><br>')?>
Prefecture: <?php print('<input type="text" name="firstname" value="' . $row['prefecture'] . '"/><br>')?>
Address: <?php print('<input type="text" value="' . $row['address'] . '"/><br>')?>
Postal Code: <?php print('<input type="text" value="' . $row['postal_code'] . '"/><br>')?>
Website: <?php print('<input type="text" value="' . $row['website'] . '"/><br>')?>
Email 1: <?php print('<input type="text" value="' . $row['email1'] . '"/><br>')?>
Contact number 1: <?php print('<input type="text" value="' . $row['phone1'] . '"/><br>')?>
<input type="button" value="Next Mosque" onclick=""/>
</form>
<?php
$mosque_id = (isset($_GET['mosque_id']) ? intval($_GET['mosque_id']) : 1); // suppose you know that '1' is the first id in your table
$result = mysql_query("SELECT * FROM Mosque WHERE mosque_id>='$mosque_id' limit 2");
$row = mysql_fetch_assoc($result); // this is the row you're gonna display in the form
$row2 = mysql_fetch_assoc($result); // this will tell us about the next row
?>
<form action="insert.php" method="post">
Mosque Name: <?php print('<input type="text" name="firstname" value="' . $row['mosque_name'] . '"/><br>')?>
Prefecture: <?php print('<input type="text" name="firstname" value="' . $row['prefecture'] . '"/><br>')?>
Address: <?php print('<input type="text" value="' . $row['address'] . '"/><br>')?>
Postal Code: <?php print('<input type="text" value="' . $row['postal_code'] . '"/><br>')?>
Website: <?php print('<input type="text" value="' . $row['website'] . '"/><br>')?>
Email 1: <?php print('<input type="text" value="' . $row['email1'] . '"/><br>')?>
Contact number 1: <?php print('<input type="text" value="' . $row['phone1'] . '"/><br>')?>
<input type="button" value="Next Mosque" onclick="window.location = 'path-to-your-page?mosque_id=<?php echo $row2['mosque_id'];"/>
</form>
First: please use mysqli functions or PDO class, not mysql functions, they are deprecated.
Secondly: use long PHP tags
But You are on right track:
Replace Your first row with:
$mosque_id = (isset($_GET['mosque_id']) ? intval($_GET['mosque_id']) : 1);
And in the end
<input type="button" value="Next Mosque" onclick="javascript: document.location = '?mosque_id=<?php echo ($mosque_id + 1);?>"/>
You also need to write some checks after query, if such id exists and actually, if you develop further, you need to check for next mosque_id also, because if you delete some rows, id-s may not be in correct order like 1, 2, 3, 4 but 1, 3, 7, 9
(hint: for next id use WHERE mosque_id > current_id ORDER BY mosque_id DESC LIMIT 1 in MySQL)
Just have a hidden input holding the ID, and increment it when the page loads. Then, when you submit, the ID will be submitted too.
<?
if (isset($_POST['id']) {
$id = $_POST['id'];
}
else {
$id = 1;
}
$result = mysql_query("SELECT * FROM Mosque WHERE mosque_id='$id'");
...
?>
<form action="insert.php" method="post">
...
<input type='hidden' name='id' value='<?php echo $mosque_id++; ?> />
<input value="Next Mosque" />
</form>
And by the way, use PDO. It's very easy to learn and adds a huge level of security to your application.

Unknown Column In Where Clause mysql query

My query is $query = "SELECT * FROM cartmatch WHERE CARTNO=$cart4"; and I'm receiving an error that says "Unknown column 'M833' in 'where clause'". Just so you know, cart4=M833.
::EDIT::
For some reason, nothing is showing. Here is the code on the page.
<?php
$cart1 = rawurldecode($_GET["path"]);
list( , , , , , $cart2) = explode ("\\", $cart1);
$cart3 = $cart2;
list($cart4) = explode (" ", $cart3);
$con = mysql_connect("SERVER","USERNAME","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cartmatch", $con);
$result = mysql_query("SELECT * FROM cartmatch WHERE CARTNO='$cart4'");
while($row = mysql_fetch_array($result))
{
echo '<form enctype="multipart/form-data" action="album.php" method="POST">Please enter press save.<br><br><input name="ID" type="hidden" value=';
echo $_GET["ID"];
echo ' ><input name="enabled" type="hidden" value=';
echo $_GET["enabled"];
echo ' ><input name="artist" type="hidden" value=';
echo $_GET["artist"];
echo ' ><input name="title" type="hidden" value="';
echo $_GET["title"];
echo '" >Name:<br/><input name="album" type="text" autofocus="autofocus" value="';
echo $row['ALBUM'];
echo '" ><input type="submit" name="edit" value="Save"></form>';
}
mysql_close($con);
?>
Change the query to:
"SELECT * FROM cartmatch WHERE CARTNO='$cart4'"
and change
list($cart4) = explode (" ", $cart3);
to
list($cart4) = explode ("+", $cart3);
Change the WHERE section to
CARTNO='$cart4'

PHP How to add multiple entries into database with checkbox form? Form only enters last entry?

Here's my code, not sure what I'm doing wrong here... First I check for the passed variable and add the bit about how to handle the form...
// Check for a user id:
if (empty($_POST['user_id'])) {
$errors[] = 'Oops! You forgot to enter your users.';
} else {
$user_id = mysqli_real_escape_string($dbc, trim($_POST['user_id']));
}
if (empty($errors)) { // If everything's good.
// Add the user to the database:
$q = "INSERT INTO users (user_id, page_id, account_id ) VALUES ('$user_id', '$page_id', '$id' )";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
//CLOSE UP THE SUBMIT CONDITIONAL
Then I select the users and echo the form
echo '<form action="addusers.php" method="post">';
while ($row = mysqli_fetch_array($show, MYSQLI_ASSOC)) {
echo '<p><label for="learner">Add</label>
<input type="checkbox" id="user_id" value="' . $row['user_id'] . '" name="user_id" /></p>';
}
echo '<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted" value="TRUE" />
<input type="hidden" name="account_id" value="$id" />
<input type="hidden" name="course_id" value="$course_id" />
</form>';
This creates a list of my users, and allows me to select as many as I like, but when I click to submit, it only enters the last user into the database, not all of them?
// UPDATE
Okay- I've edited the code so that the value of the checkbox is an array and know I need to use the foreach loop to pass the variables into the database, but could someone check this code for that insert?
// Add the user to the database:
$q = "INSERT INTO users (user_id) VALUES ('$user_id')";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
foreach($_POST as $key => $value){
if ($r->execute(Array($key, $value))){
echo "user added <br />";
}
} // end for each loop
Use:
<input type="checkbox" id="user_id" value="' . $row['user_id'] . '" name="user_id[]" />
(note the [] after user_id in the "name" attribute).
That will cause $_POST['user_id'] to be an array of values, one for each checked checkbox.
try this replace
<input type="checkbox" id="user_id" value="' . $row['user_id'] . '" name="user_id" /></p>';
by
<input type="checkbox" id="user_id" value="' . $row['user_id'] . '" name="user_id[]" /></p>';
// try to make your user_id checkbox as array like user_id[]

Implementing Gravatar into custom Commenting System

I'm in the process of coding my very first blog. With the help of various tutorials, and other forums I have managed to gather a semi-working code.
Right now I have a code that takes and displays the comment, but the problem is I wish to display Gravatars beside each comment. I was just wondering how exactly I would go about implementing the code that they provided on their website.
Here is my current comment form:
<?php
}
$commenttimestamp = strtotime("now");
$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$timestamp = date("l F d Y", $row['timestamp']);
printf("<hr />");
print("<p>" . stripslashes($row['comment']) . "</p>");
printf("<p>Comment by %s # %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
printf("<hr />");
}
?>
<form method="post" action="process.php">
<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />
<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">
<strong><label for="name">Name:</label></strong> <input type="text" name="name" id="name" size="25" /><br />
<strong><label for="email">E-mail:</label></strong> <input type="text" name="email" id="email" size="25" /><br />
<strong><label for="url">URL:</label></strong> <input type="text" name="url" id="url" size="25" value="http://" /><br />
<strong><label for="comment">Comment:</label></strong><br />
<textarea cols="25" rows="5" name="comment" id="comment"></textarea></p>
<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>
</form>
If you wish for me to post the php that processes each comment here as well just ask below.
My code now:
<?php
function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
$url = 'http://www.gravatar.com/avatar/';
$url .= md5( strtolower( trim( $email ) ) );
$url .= "?s=$s&d=$d&r=$r";
if ( $img ) {
$url = '<img src="' . $url . '"';
foreach ( $atts as $key => $val )
$url .= ' ' . $key . '="' . $val . '"';
$url .= ' />';
}
return $url;
}
}
$commenttimestamp = strtotime("now");
$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$timestamp = date("l F d Y", $row['timestamp']);
printf("<hr />");
print("<p>" . stripslashes($row['comment']) . "</p>");
printf("<p>Comment by %s # %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
echo $imagetag = "<img src='" . get_gravatar($email) . "' />";
printf("<hr />");
}
?>
You want an image tag whose src comes from the gravatar function.
Something like:
$imagetag = "<img src='" . get_gravatar($email_address) . ' />";
(You'll need to echo this variable where you want it to display.)
The only required parameter of the get_gravatar function is the email address, so just pass this to get_gravatar and you get the url of the gravatar image.
You also may use the Libravatar service that provides a gravatar-compatible but open source and federated alternative.
It has a nice PHP library - Services_Libravatar - that's easy to use:
<?php
require_once 'Services/Libravatar.php';
$sla = new Services_Libravatar();
$imgUrl = $sla->getUrl('foo#example.org');

Categories