PHP search script for multiple words - php

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);
}
}

Related

Insert batch to MySQL with PHP/PDO

I have an form for bulk add domains and these domains could have one or more countries and one language attribute.
My form (reduced to code):
Add domains:
<textarea name="bulk" rows="10" class="form-control no-resize"><?php echo $_POST['bulk']; ?></textarea>
Choose one or more countries:
<div class="checkbox">
<?php
if ($queries->query("SELECT * FROM countrycodes ORDER BY code ASC")) {
if ($queries->count() > 0) {
$contents = $queries->fetchAll();
foreach ($contents as $content) {
?>
<input type="checkbox" id="country_<?php echo $content->code; ?>" name="country[]" value="<?php echo $content->code; ?>" <?php if (in_array($content->code, $_POST['country'])) echo "checked = 'checked'"; ?> />
<label for="country_<?php echo $content->code; ?>"><?php echo $content->country; ?></label><br />
<?php }}} ?>
</div>
Choose the language:
<div class="radio">
<?php
if ($queries->query("SELECT * FROM langcodes ORDER BY code ASC")) {
if ($queries->count() > 0) {
$contents = $queries->fetchAll();
foreach ($contents as $content) {
?>
<input type="radio" name="lang" id="lang_<?php echo $content->code; ?>" value="<?php echo $content->code; ?>" <?php if ($content->code == $_POST['lang']) { ?>checked="" <?php } ?> />
<label for="lang_<?php echo $content->code; ?>"><?php echo $content->language; ?></label><br />
<?php }}} ?>
</div>
Get data from submit:
if (isset($_POST['addData'])) {
$doms = explode("\n", str_replace("\r", "", $_POST['bulk']));
$coun = implode(", ", $_POST['country']);
$lang = $_POST['lang'];
}
I found this one for bulk inserts:
$d = ['Osian', 'Williams', 1];
$data = array_fill(0, 1000, $d);
$db = new PDO('mysql:host=localhost;dbname=MYDB','MYUSER','MYPASS');
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO members (firstname, surname, title) VALUES (?,?,?)');
for($i=0;$i<count($data);$i++) {
$stmt->execute($data[$i]);
}
$db->commit();
I have no idea, how to get my data (domains, countries, lang) working for this code.
And, I need to check if a domain is already in the db, but only, if the domain has the same language.
So, would be nice to get some help.
I found an solution. Was a bit confused at the beginning, how to add country and lang to the list of domains. But the country data and lang data are static - so I just need to loop through the domains.
That's my solution and it works:
if (isset($_POST['addData'])) {
$doms = explode("\n", str_replace("\r", "", $_POST['bulk']));
$coun = implode(", ", $_POST['country']);
$lang = $_POST['lang'];
$queries->transStart();
foreach ($doms as $dom) {
if ($queries->query("SELECT domain FROM websites WHERE domain = ? AND lang = ?", [$dom, $lang])) {
if ($queries->count() > 0) {
$infoBox = "error_duplicate";
} else {
$queries->query("INSERT INTO websites (domain, country, lang) VALUES (?,?,?)", [$dom, $coun, $lang]);
$infoBox = "success";
}
}
}
$queries->transStop();
}

PHP foreach array_combine [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the following code:
// choices array
$choices = [];
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$titlu = [];
$titlu[1] = $_POST['titlu1'];
$titlu[2] = $_POST['titlu2'];
$titlu[3] = $_POST['titlu3'];
if($insert_row){
foreach(array_combine($choices, $titlu) as $choice => $titlu)
{
if($choice != ''){
if($correct_choice == $choice) {
$is_correct = 1;
} else {
$is_correct = 0;
}
$query = "INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('$question_number', '$is_correct', '$choice', '$titlu')";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row) {
continue;
} else {
die('Error : ('.$mysqli->errno.') ' . $mysqli->error);
}
}
}
$msg = "Questions has been added";
}
}
My database tables are:
"Choices" which contain:
---------------------------------------------------
id | question_number | is_correct | choice | titlu |
---------------------------------------------------
My old code was without "titlu" row, i added it, and i used "aray_combine" for that .
Everything is working fine, rows are filled with info, but "is_correct" row don't work anymore. It show only "0" on all rows, even i select to show "1" .
Hope you understand me! I'm begginer, but i'm ready to learn.
Thank you!
I am not sure where are you getting your correct_choice value from.. but i did a quick test and it's working as expected.
$choices = [];
$choices[1] = 'bar';
$choices[2] = 'foo';
$choices[3] = 'elo';
$correct_choice = 'foo'; //added
$titlu = [];
$titlu[1] = 'llo';
$titlu[2] ='plo';
$titlu[3] = 'clo';
foreach(array_combine($choices, $titlu) as $choice => $titlu)
{
if($choice != ''){
if($correct_choice == $choice) {
$is_correct = 1;
} else {
$is_correct = 0;
}
$query = "INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('1', '$is_correct', '$choice', '$titlu')";
echo $query . "<br/>";
}
}
$msg = "Questions has been added";
output is
INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('1', '0', 'bar', 'llo')
INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('1', '1', 'foo', 'plo')
INSERT INTO `choices`(question_number, is_correct, choice, titlu)VALUES('1', '0', 'elo', 'clo')
may be there is something wrong with the way your correct_choice
Here is my HTML form:
<form method="post" action="add.php">
<p>
<label>Question Number</label>
<input type="number" value="<?php echo $next; ?>" name="question_number" />
</p>
<p>
<label>Question</label>
<input type="text" name="question_text" />
</p>
<p>
<label>Choice #1: </label>
<input type="text" name="choice1" />
</p>
<p>
<label>Choice #2: </label>
<input type="text" name="choice2" />
</p>
<p>
<label>Choice #3: </label>
<input type="text" name="choice3" />
</p>
<p>
<label>TITLU #1: </label>
<input type="text" name="titlu1" />
</p>
<p>
<label>TITLU #2: </label>
<input type="text" name="titlu2" />
</p>
<p>
<label>TITLU #3: </label>
<input type="text" name="titlu3" />
</p>
<p>
<label>Correct choice number </label>
<input type="number" name="correct_choice" />
</p>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
</form>
I think here is my problem:
if($choice != ''){
if($correct_choice == $choice) {
$is_correct = 1;
} else {
$is_correct = 0;
}
Before to add "titlu" row and his values, there was filled with "$value", but i changed with "$choice"

Insert several rows at once MySql DB

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";
...
}

I can't select my users level from the DB, codeigniter

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

Search multiple words and single word at a time in a multiple row in Mysql php

I'm trying to use this search for searching more than one words or single word at a time from a database. Now the problem is that my script only running properly but please help me...
<form name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<!--<input type="text" name="search" placeholder="Location" />-->
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
<?
$conn=mysql_connect("localhost","root","");
mysql_select_db("dbrozgarexpress",$conn);
echo $search =$_POST['location'];
$description = "";
$name2=$_POST['name'];
if(isset($name2)&&$name2 != ""){
if($flag){
$cheack.= "AND ";
}
$cheack.="user_first_name ='$name2' ";
$flag =true;
}
if(isset($search)&&$search != ""){
if($flag){
$cheack.= "AND ";
}
foreach($search AS $s)
{
$cheack.="user_current_location_id ='$s' or ";
$flag =true;
}
}
$cheack = substr($cheack, 0, -4);
echo $query = "SELECT * FROM `tb_user` WHERE $cheack ";
?>
error SELECT * FROM `tb_user` WHERE user_first_name ='kum
I think I have a general idea of what you are after.
P.S. the query will only show after you submit the form - i.e. after you click search button
Try this:
<?php
// Handle Post
if (count($_POST))
{
// Load Params
$name = isset($_POST['name']) ? $_POST['name'] : '';
$locations = isset($_POST['location']) ? $_POST['location'] : array();
// Start Query
$sql = 'SELECT * FROM `tb_user` WHERE ';
// Build Query
$sql_parts = array();
if (!empty($name)) {
$sql_parts[] = "`user_first_name` = '$name'";
}
if (sizeof($locations)) {
foreach ($locations as $location) {
$sql_parts[] = "`user_current_location_id` = '$location'";
}
}
$sql = $sql . implode(' AND ', $sql_parts);
// Debug
echo $sql ."<br><br>";
}
?>
<form action="" name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
Here's an example of this working:
No location selected, name only
name and one location
name and two location

Categories