Here is my code to add multiple types to table. I want to combine areas, location, types and add them in the table at once. I think this just wont work if(!empty($_POST['types'] && $_POST[''] && $_POST[''] ) Thanks!
if(!empty($_POST['types'])) {
$values = array();
foreach($_POST['types'] as $typ_id) {
$values[] = sprintf('(%d, %d)', $station_id, $typ_id);
}
$query = 'INSERT IGNORE INTO station_typ_tab
(station_id, typ_id, area_id, location_id)
VALUES ' .
implode(',', $values);
mysql_query($query, $db) or die(mysql_error($db));
}
EDIT: here is part of code for types[] and same is for areas and location
<td>Types:<br/> <small>CTRL + click to set multiple pollutants</em></small>
</td>
<td>
<?php
$query = 'SELECT typ_id, typ FROM typ_tab ORDER BY typ ASC';
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
echo '<select multiple name="types[]">';
while ($row = mysql_fetch_array($result)) {
if (isset($station_typ[$row['typ_id']])) {
echo '<option value="' . $row['typ_id'] . '"
selected="selected">';
} else {
echo '<option value="' . $row['typ_id'] .'">';
}
echo $row['typ'] . '</option>';
}
echo '</selected>';
} else {
echo '<p><strong>Databaza je prazdna... Enter database</strong></p>';
}
mysql_free_result($result);
how to combine $_POST for types, location and areas if they comes from different selecting input. something like if(!empty($_POST['types'] && $_POST['areas'] && $_POST['location']) ){ $values = array(); foreach( NEW VARIABLE as $typ_id && area_id &&location_id) { $values[] = sprintf('(%d, %d, %d, %d)', $station_id, $typ_id, area_id, location_id); if it is possible to do it like this
to combine in IF try to use
if((!empty($_POST['types'])) && (!empty($_POST['area'])) && (!$_POST['location'])));
Related
I need to be able to save selected items from a multi select drop-down list into a MySQL DB and display all the selected items. When I hit submit only the last item is saved.
Code originally was for a single item to be selected from a drop-down menu. I have modified it for selecting multiple items (for ease of editing by other people). I have tried various solutions including if is_array, for loops and foreach loops without any luck. Can anyone point me in the right direction please.
HTML code
<select name="topic_id[]" multiple="multiple" id="select">
<?php
$topic_set = find_all_topics();
while($topic = mysqli_fetch_assoc($topic_set)) {
foreach($topic_set as $topic) {
echo "<option value=\"" . $topic['id'] . "\"";
if($page['topic_id'] == $topic['id']) {
echo " selected";
}
echo ">" . $topic['menu_name'] . "</option>";
}
}
mysqli_free_result();
?>
</select>
PHP
function insert_page($page) {
global $db;
$errors = validate_page($page);
if(!empty($errors)) {
return $errors;
}
shift_page_positions(0, $page['position'], $page['topic_id']);
$post_t_ids = array();
foreach($_POST['topic_id'] as $post_t_id) {
$post_t_ids[] = (int) $post_t_id;
}
$post_t_id_joined = join('), (', $post_t_ids);
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $post_t_id_joined) . "',";
$sql .= "'" . db_escape($db, $page['content']) . "'";
$sql .= ")";
$result = mysqli_query($db, $sql);
if($result) {
return true;
} else {
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
if(is_post_request()) {
$page = [];
$page['topic_id'] = $_POST['topic_id'] ?? '';
$page['content'] = $_POST['content'] ?? '';
$result = insert_page($page);
if(!isset($_POST['topic_id'])) {
$_POST['topic_id'] = [];
}
if($result === true) {
$new_id = mysqli_insert_id($db);
} else {
$errors = $result;
}
}
The result should be selecting multiple items from the drop-down list and upon clicking submit all selected items should save to the DB and displayed to a different page. No error messages pop up but only the last item selected gets saved and displayed.
Your part to make an sql statement is wrong. It will produce you something like:
INSERT INTO pages (topic_id, content) VALUES ('1), (2), (3','content')
You need to modify your code to get a proper sql statement. Of course, I would recommend you to use prepared statements:
$params['content'] = $page['content'];
$stmt = $mysqli->prepare('INSERT INTO pages (topic_id, content) VALUES (:id, :content)');
foreach($_POST['topic_id'] as $id) {
$params['id'] = $id;
$stmt->execute($params);
}
If you still want to use your approach, you should do it like this:
$content = $page['content'];
$makeValues = function($id) use ($content) {
return "($id, '$content')";
};
$post_t_id_joined = implode(', ', array_map($makeValues, $post_t_ids));
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES $post_t_id_joined";
I have 3 tables:
people:
------------------------
peopleID,
firstname
peopletype:
------------------------
peopletypeID,
type
peoplepeopletype (junction table):
------------------------
peopleID,
peopletypeID
On the add form everything is fine, but I have problem to display checkboxes checked for the assigned peopletype
Here is my code.
Retrieve data from peoplepeopletype table :
/*PEOPLE TYPE ************* */
$stmt = $conn->prepare("SELECT * FROM peoplepeopletype WHERE peopleID=?");
// set parameters and execute
if ( !$stmt ) { echo "error"; }
else if ( !$stmt->bind_param('i', $_GET['peopleID']) ) { echo "error";}
else if ( !$stmt->execute() ) { echo "error"; }
else {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$peopletypeIDfromdb = $row ['peopletypeID'];
echo $peopletypeIDfromdb; /*echo only for test purposes, but I don't know how to use this in the form */
}
} /* end else */
Display checkboxes :
<?php /*retrieve peopletype from db */
$sql = "SELECT * from peopletype";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' . $row["peopletypeID"] . '"';
if ($peopletypeIDfromdb = $row["peopletypeID"]) { /*problem is probably here*/
echo 'checked';
}
echo '>' . $row["type"];
}
?>
Thanks for your help!
If you can have multiple types attached to 1 person, you'll need to change the first loop to store all of them in an array. I store them as keys to have the minimum complexity of checking the existence of certain type in the future among the types assigned to the person.
$result = $stmt->get_result();
$types = array();
while($row = $result->fetch_assoc()) {
$types[$row ['peopletypeID']] = 1;
}
And then use it inside the second loop:
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' .
$row["peopletypeID"] . '" ';
if(isset($types[$row["peopletypeID"]]))
{
echo 'checked';
}
echo '>' . $row["type"];
}
How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!
Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}
I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";
You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it
this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone
First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";