I have a form with 6 text inputs for users to add some links to them and add them do a database. Each one of these 6 inputs insert data in a different row. This is my code:
public function insertImages($img1,$img2,$img3,$img4,$img5,$img6){
$myDb = $this->_controlPanel->getMyDb();
$query = "INSERT INTO galeria (img) VALUES ('$img1'), ('$img2'),('$img3'), ('$img4'),('$img5'), ('$img6')";
$result = $myDb->performQuery($query);
if (!$result) {
die('Something went wrong, try again: ' . mysql_error());
header( "Refresh:3; url=insertnot.php");
}
else {
header( "Refresh:1; url=admin.php");
}
}
and
if(!empty($_POST)){
$img1 = $_POST['img1'];
$img2 = $_POST['img2'];
$img3 = $_POST['img3'];
$img4 = $_POST['img4'];
$img5 = $_POST['img5'];
$img6 = $_POST['img6'];
try{
$log = new classes_UserManager($myControlPanel);
$insert = $log->insertImagens($img1,$img2,$img3,$img4,$img5,$img6);
}
catch (invalidArgumentException $e){
$e->getMessage();
}
}
?>
<div class="container">
<h2 style="color:#666; margin-top:15vh; text-align:center;"> Inserir Imagens </h2>
<form style="margin-top:10vh;" name="img" method="POST" action="">
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 1" class="form-control" type="text" name="img1" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 2" class="form-control" type="text" name="img2" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 3" class="form-control" type="text" name="img3" id="title" >
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 4" class="form-control" type="text" name="img4" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 5" class="form-control" type="text" name="img5" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 6" class="form-control" type="text" name="img6" id="title" >
</div>
</div>
<br>
<br>
<input type="submit" style="width:100%; margin:0 auto;" class="btn btn-primary form-control" name="submit" id="submit">
This is working well, but how do i avoid entering blank rows when the user only fills like two or three inputs?
Use the "power" of concatenation. There are few solutions to your problem.
let's consider following function:
<?php
// get all non-empty fields for POST that
// have index like img<number>
function getNonEmptyValues ($inputs , $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
}
return $nonempty_inputs;
}
// get all non-empty fields for POST that
// have index like img<number>
// but ignore all fields after 1 missing,
// e.g. : img1, img2, img3 return array of length 3
// while img1, img2, img4 will return array of length 2
function getInOrder($inputs, $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
else
{
break;
}
}
return $nonempty_inputs;
}
function buildInsertQuery ($inputs) {
if (count($inputs) === 0) {
throw new \Exception("Missing inputs. Cannot build query.");
}
$query = "INSERT INTO galeria (img) VALUES ";
$insert_values = [];
foreach( $inputs as $value ) {
$insert_values []= "('".$value."')";
}
return $query . implode(",", $insert_values) . ";";
}
$_our_post = array(
"img1" => "kittenz",
"img2" => "doge",
"img4" => "me gusta"
);
$my_data = getNonEmptyValues($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
$my_data = getInOrder($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
something like this:
if(!empty($_POST)) {
$images = array();
for ($i = 1; $i <= 6; $i++) {
if (!empty($_POST['img'.$i]))
$images[] = $_POST['img'.$i];
}
if (sizeof($images) > 0)
$insert = $log->insertImages($images);
...
}
and
public function insertImages($images) {
$myDb = $this->_controlPanel->getMyDb();
$imgStr = '';
foreach($images as $k => $v) {
$imgStr += "('$v'),";
}
$imgStr = rtrim($imgStr, ','); // remove trailing comma
$query = "INSERT INTO galeria (img) VALUES $imgStr";
...
}
Related
enter image description hereI'm trying to insert multiple text-boxes with only two names.In all these texboxes I have names items[] and qty[]. I have tried to nest foreach loop but adds more values than expected.The problem is with $_POST['qty']. I can select and add from items[], but I can not add the qty integer value!
<div class="col-md-12 diff">
<div class="col-md-4">
<p>Select Item</p>
<input style="color:black;" type="text" class="form-control items" name="items[]" placeholder="Search...">
<div class="side"></div>
</div>
<div class="col-md-2">
<p>QTY</p>
<input id="pats_input" class="form-control pats_tb" type="text" name="qty[]" placeholder="NO:">
<div class="side"></div>
</div>
</div>
<div class="col-md-12 diff">
<div class="col-md-4">
<p>Select Item</p>
<input style="color:black;" type="text" class="form-control items" name="items[]" placeholder="Search...">
<div class="side"></div>
</div>
<div class="col-md-2">
<p>QTY</p>
<input id="pats_input" class="form-control pats_tb" type="text" name="qty[]" placeholder="NO:">
<div class="side"></div>
</div>
</div>
function issueToEmployee(){
global $conn;
if(isset($_POST['pats']) && $_POST['pats'] !="" && isset($_POST['items']) && $_POST['items'] !="" && isset($_POST['qty'])){
$perstat = new getPerstat();
//get employee pats
$perstat->getPats($_POST['pats']);
$stock = new StockTable();
$qty = $_POST['qty'];
foreach($_POST['items'] as $item){
foreach($qty as $q){
if(!empty($item) && !empty($q)){
$stock->getItemByName($item);
$sql = $conn->prepare("INSERT INTO issues (empid, itemid) VALUES('$perstat->id','$stock->itemid')");
$sql->execute();
}
}
}
return true;
}else{
return false;
}
I think you're trying to point the items on the qty like this:
$items = $_POST['items'];
$qty = $_POST['qty'];
foreach($items as $i => $item)
{
if(!empty($item) && (isset($qty[$i]) && !empty($qty[$i])))
{
$stock->getItemByName($item);
$sql = $conn->prepare("INSERT INTO issues (empid,itemid) VALUES('$perstat->id','$stock->itemid')");
$sql->execute();
}
}
Since Items are corresponds to their qty (correct me if I'm wrong)
I found how to add above values from multiple input fields items[] and qty[],
for($i = 0; $i < 8 ; $i++){
//$id = $_POST['id'][$i];
$description = $_POST['items'][$i];
$qty = $_POST['qty'][$i];
$date = $_POST['date'];
if(!empty($qty)){
$stock->getItemByName($description);
$sql = $conn->prepare("INSERT INTO issues (empid, itemid, qty, date) VALUES('$perstat->id','$stock->itemid','$qty','$date')");
$sql->execute();
}
}
i want show lot's of data in multiple page where every page contains 20 data. i am searching the data after giving few value in post using form. but the post value is working for the first page during show the data. from the 2nd page the post value is not working. Below is my code of action page..
<?php
$conn = mysql_connect("localhost","root","1amShaw0n");
mysql_select_db("bkash_plus",$conn);
$account_no = $_POST['account_no'];
$remarks = $_POST['remarks'];
$open_by= $_SESSION['user_name'];
$result = mysql_query("SELECT count(*) as count FROM tickets where created_by='$open_by' and status='Closed' and account_no like '%$account_no%' and remarks like '%$remarks%'");
if(false === $result) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
while ($row = mysql_fetch_assoc($result)) {
$row_count= $row['count'];
}
}
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$items_per_page = 20;
$page_count = (int)ceil($row_count / $items_per_page);
$page = 1;
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
// make your LIMIT query here as shown above
// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 20;
// build query
$offset = ($page - 1) * $items_per_page;
// Collects data from "friends" table
$data = mysql_query("SELECT * FROM bkash_plus.tickets where created_by='$open_by' and status='Closed' and account_no like '%$account_no%' and remarks like '%$remarks%' order by tickets_id desc LIMIT " . $offset . "," . $items_per_page)
or die(mysql_error());
// $result = mysql_query($data) or die ("Error in query: $data. ".mysql_error());
// puts the "friends" info into the $info array
//$info = mysql_fetch_array( $data );
if (mysql_num_rows($data) >= 0) {
echo '<table border="2" width="1030px">
<tr>
<th><center><font color="blue">Ticket_ID</font><center></th>
<th><center><font color="blue">Account No</font><center></th>
<th><center><font color="blue">Created Time</font><center></th>
<th><center><font color="blue">Service Type</font><center></th>
<th><center><font color="blue">Category</font><center></th>
<th><center><font color="blue">Sub_Category</font><center></th>
<th><center><font color="blue">Status</font><center></th>
<th><center><font color="blue">Remarks</font><center></th>
<th><center><font color="blue">Created By</font><center></th>
</tr>';
while($info = mysql_fetch_array($data)){
echo '
<tr>
<td><center><a href=ticket_view_data_front.php?tickets_id='.$info['tickets_id'].'>'.$info['tickets_id'].'</a><center></td>
<td><center>'.$info['account_no'].'<center></td>
<td><center>'.$info['created_time'].'<center></td>
<td><center>'.$info['service_type'].'<center></td>
<td><center>'.$info['category'].'<center></td>
<td><center>'.$info['sub_category'].'<center></td>
<td><center>'.$info['status'].'<center></td>
<td><center>'.$info['remarks'].'<center></td>
<td><center>'.$info['created_by'].'<center></td>
</tr>';
}
echo '</table>';
}
// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
if ($i === $page) { // this is current page
echo 'Page ' . $i . '';
} else { // show link to other page
echo '>>';
echo 'Page ' . $i . ' ';
}
}
?>
here "view_all_ticket_front_closed_search_result.php" is the action page..
For the first page i got the result of first 20 rows but during 2nd page i am getting below error...
Notice: Undefined index: account_no in C:\xampp\htdocs\bkash_plus\view_all_ticket_front_closed_search_result.php on line 74
Notice: Undefined index: remarks in C:\xampp\htdocs\bkash_plus\view_all_ticket_front_closed_search_result.php on line 75
Below is the form page that passing the POST value..
<form method="post" class="form-horizontal" role="form">
<!-- Account No: <input type="text" name="account_no">
ID: <input type="text" name="id">
<input type="submit" name="submit" value="Check"> -->
<div class="form-group">
<label class="control-label col-sm-2" for="account_no">Account ID:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="account_no" name="account_no" style="height:35px;width:160px">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="remarks">Remarks:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="remarks" name="remarks" style="height:35px;width:160px">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 ticket">
<input type="submit" class="btn" name="submit" value="View" formaction="view_all_ticket_front_closed_search_result.php">
</div>
</div>
</form>
Anyone please help me to fix this issue.
im trying to get from my DB, the levels from a users, and print them in a view, but i cant do it.
Controller:
public function add_notificacion() {
$data = array();
if (!empty($this->input->post('mensaje', TRUE))) {
if (($this->input->post('id_profesor', TRUE) != 0)) {
$id_profesor = $this->input->post('id_profesor', TRUE);
$this->load->model('Profesor_model', 'profesor');
$json_data = $this->profesor->gets_profesor($id_profesor);
foreach ($json_data as $fila) {
$nivel[] = $fila->id_nivel;
}
} else {
$nivel = $this->input->post('niveles', TRUE);
}
View:
div class="col-md-5 col-sm-5 col-xs-5">
<label for="niveles">Niveles</label>
</div>
<div class="col-md-14 col-sm-25 col-xs-25">
<?php if ($temp == 0) { ?>
<input id="todo" name="todo" type="checkbox"> Todos <br>
<?php } ?>
<?php
if(!empty($nivel)){
foreach ($nivel as $fila) {
if (in_array($fila->id_nivel, $id_nivel[0])) {
?>
<input disabled="disabled" id="nivel" class="che" name="niveles[]" type="checkbox" value="<?= $fila->id_nivel ?>" checked="" onclick="checkAddress(this)" style="cursor:auto;"> <?= $fila->nombre . " " . $fila->seccion ?><br>
<div id="repre"> </div>
<?php
} else {
?>
Model:
function gets_profesor($id_profesor) {
$result = $this->db->get_where('profesor', array('id_profesor =' => "$id_profesor"));
return $result->result();
}
The form just show me the "Todos" checkbox, but I need to print every "Nivel" user.
Sorry for my novice code but this might help.
Say if you have a table called "users" and a field called "level" and another called "username".
$getlevels = mysqli_query($con,"SELECT * FROM users");
while($r = mysqli_fetch_array($getlevels)){
$username = $r['username'];
$level = $r['level'];
echo $username," - ",$level,"<br>";
}
That will show each user and their levels afterwards
I have the following issue:
I can't search multiple words.
I have a search engine who search just the full string:
PHP Code:
function ft_search_sidebar() {
$sidebar[] = array(
"id" => "search_1",
"content" => '<div class="section">
<h2>'.t('Search files & folders').'</h2>
<form action="" method="post" id="searchform">
<div>
<input type="text" name="q" id="q" size="16" value="'.$_REQUEST['q'].'" />
<input type="button" id="dosearch" value="'.t('Search').'" />
</div>
<div id="searchoptions">
<input type="checkbox" name="type" id="type" checked="checked" /> <label for="type">'.t('Search only this folder and below').'</label>
</div>
<div id="searchresults"></div>
</form>
</div>'
);
return $sidebar;
}
function ft_search_ajax($act) {
if ($act = '%search%') {
$new = array();
$ret = "";
$q = $_POST['q'];
$type = $_POST['type'];
if (!empty($q)) {
if ($type == "true") {
$list = _ft_search_find_files(ft_get_dir(), $q);
} else {
$list = _ft_search_find_files(ft_get_root(), $q);
}
Can someone help me?
Grtz
You will need to either develop a search engine which is capable of multi keyword search or simply extract out all the keywords from the search string and then use the search engine multiple times for each keyword. Like this:
$q = $_POST['q'];
$type = $_POST['type'];
if (!empty($q)) {
if(strpos(trim($q),' ') > 0)
{
$array = explode(' ',trim($q));
foreach($array as $key=>$value)
{
//process search multiple times for different values of $value
}
}
else
{
if ($type == "true")
{
$list = _ft_search_find_files(ft_get_dir(), $q);
}
else
{
$list = _ft_search_find_files(ft_get_root(), $q);
}
}
I'm trying to insert multiple values into my database, the values are from a jQuery script that generate a tags when you click space.
I tried to put a name on the tag, but it only insert into the database, the last tag, i want to insert all tags.
Here my code
<script type='text/javascript'>
$(window).load(function(){
function closer(){
$('#close').live('click', function() {
$(this).parent().remove();
});
}
$('#tags').keypress(function(e) {
if(e.which == 32) {
var tx = $('#tags').val();
if (tx) {
$(this).val('').parent().before('<li class="tags"><span><input type="hidden" value="'+tx+'" name="tags">'+tx+'</input></span><a style="cursor:pointer;" id="close">[x]</a></li>');
closer();
}
}
});
});
</script>
<?php
include(PATH_MODULE . '/joboffers/view/joboffers_view.php');
//add job offer function
function addjo(){
connect();
addjoview();
//check if the button was clicked
if (isset($_POST['add_jo'])){
if ($_POST['job_category']) {
$job_category = mysql_real_escape_string($_POST['job_category']);
$check1 = 0;
} else {
$check1 = 1;
}
if ($_POST['description']) {
$description = mysql_real_escape_string($_POST['description']);
$check2 = 0;
} else {
$check2 = 1;
}
if ($_POST['job_name']) {
$job_name = mysql_real_escape_string($_POST['job_name']);
$check3 = 0;
} else {
$check3 = 1;
}
if ($_POST['hiring_manager']) {
$hiring_manager = mysql_real_escape_string($_POST['hiring_manager']);
$check4 = 0;
} else {
$check4 = 1;
}
if ($_POST['tags']) {
$tags = mysql_real_escape_string($_POST['tags']);
$check5 = 0;
} else {
$check5 = 1;
}
if ($_POST['localization']) {
$localization = mysql_real_escape_string($_POST['localization']);
$check6 = 0;
} else {
$check6 = 1;
}
if ($_POST['attributes']) {
$attributes = mysql_real_escape_string($_POST['attributes']);
$check7 = 0;
} else {
$check7 = 1;
}
if ($_POST['contract_type']) {
$contract_type = mysql_real_escape_string($_POST['contract_type']);
$check8 = 0;
} else {
$check8 = 1;
}
if ($_POST['professional_exp']) {
$professional_exp = mysql_real_escape_string($_POST['professional_exp']);
$check9 = 0;
} else {
$check9 = 1;
}
//verify if all fields are right
if ($check1 == 0 && $check2 == 0 && $check3 == 0 && $check4 == 0 && $check5 == 0 && $check6 == 0 && $check7 == 0 && $check8 == 0 && $check9 == 0){
$query =("INSERT INTO job_offers (job_category, description, job_name, hiring_manager, tags, localization, attributes, contract_type, profissional_experience) VALUES ('" . $job_category . "','" . $description . "','" . $job_name . "','" . $hiring_manager . "','" . $tags . "', '" . $localization . "', '" . $attributes . "', '" . $contract_type . "', '" . $professional_exp . "')");
db_query($query, '+');
echo "Congratulations! You have been successfully registered in our system.";
} else {
echo "Ops, something went wrong!";
}
}
}
?>
HTML
<form method="POST">
<br>
<label>Job category</label>
<input type="text" name="job_category" maxlength="100" >
<br><br>
<label>Description</label>
<textarea cols="22" rows="3" name="description"></textarea>
<br><br>
<label>Job name</label>
<input type="text" name="job_name" maxlength="130" >
<br><br>
<label>Hiring manager</label>
<input type="text" name="hiring_manager" maxlength="130" >
<br><br>
<label>Tags</label>
<div id="wrapbox">
<div id="box">
<input type="text" id="tags" class="tagstype" maxlength="230">
</div>
</div>
<br><br>
<label>Localization</label>
<input type="text" name="localization" maxlength="130" >
<br><br>
<label>Attributes</label>
<input type="text" name="attributes" maxlength="130" >
<br><br>
<label>Contract type</label>
<input type="text" name="contract type" maxlength="130" >
<br><br>
<label>Professional experience</label>
<input type="text" name="professional_exp" maxlength="130" >
<br><br>
<input name="add_jo" type="submit" />
</form>
Try changing this
<input type="hidden" value="'+tx+'" name="tags">
to this
<input type="hidden" value="'+tx+'" name="tags[]">
Then, in your PHP code, do something like this
if ($_POST['tags']) {
$tags = mysql_real_escape_string(implode(",", $_POST['tags']));
$check5 = 0;
} else {
$check5 = 1;
}
That will insert a comma-separated list of the tags into your tags field in your table. If you would rather have it be space-separated, simply use implode(" ", $_POST['tags']) instead.
That being said, I would suggest restructuring your database so that you do not have a tags column in your job_offers table. Instead, you would have a job_offer_tags table which would have the columns id, job_id and tag, and you only enter single tags into the tag column.