PHP script to search MySQL database - php

I have a script that is supposed to return values from a mysql tables based on search inputs. This script is composed of two files.
search.php
<?php
if ( isset( $_GET['s'])) {
require_once( dirname( __FILE__ ) . '/class-search.php' );
$search = new search();
$search_term = $GET['s'];
$search_results = $search->search($search_term);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<div class="search-form">
<form action="" method="get">
<div class="form-field">
<label for="search-field">Search</label>
<input type="search" name="s" placeholder="Search by name" results="5" value="<?php echo $search_term; ?>">
<input type="submit" value="Search">
</div>
</form>
</div>
<?php if ( $search_results ) : ?>
<div class="results-count">
<p><?php echo $search_results['count']; ?> results found</p>
</div>
<div class="results-table">
<?php foreach ( $search_results['results'] as $search_result ) : ?>
<div class="result">
<p><?php echo $search_result->title; ?></p>
</div>
<?php endforeach; ?>
</div>
<div class="search-raw">
<pre><?php print_r($search_results); ?></pre>
</div>
<?php endif; ?>
</body>
and class-search.php
<?php
class search {
private $mysqli;
public function __construct() {
$this->connect();
}
private function connect() {
$this->mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE' );
}
public function search($search_term) {
$sanitized = $this->mysqli->query("
SELECT * FROM `Apple`
FROM search
WHERE Last_Name LIKE '%{$sanitized}%'
");
if ( ! $query->num_rows ) {
return false;
}
while( $row = $query->fetch_object() ) {
$rows[] = $row;
}
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
}
?>
Within my database I have two tables, but I'm only interested in searching the content of one (Apple). Can somebody help me? I can't seem to make this work. No results are returned no matter what I search. As of now I'm only using the Last_Name criteria, but I'd like to add others. Here's a link to the screenshot of my table http://imgur.com/a/H3DnG.
I'd really appreciate any feedback possible. Thank you.

If you check it again,
In search method you're passing $search_term as argument but in the query you're using $sanitized which doesn't exists until the query is executed.
You're result set is in $sanitized but you're checking $query for num_rows which don't even exists. Also, you're returning false in that method so you're not able to identify the actual problem.
public function search($search_term) {
$sanitized = $this->mysqli->query("
SELECT * FROM `Apple`
FROM search
WHERE Last_Name LIKE '%{$search_term}%'
");
if ( ! $sanitized->num_rows ) {
//return false;
retrun [];
}
$rows = [];
while( $row = $sanitized->fetch_object() ) {
$rows[] = $row;
}
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
In connect method, add this which will tell whether its getting connected to database or not.
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
}

Related

How to store values of the index in an array?

I have an array that looks like this
Array ( [0] => test1 [1] => test4 [2] => test2 )
I got this value from my database using Codeigniter built-in function
And whenever I try to insert this value back in my database, it's inserting the index instead of the value itself
The error I'm getting is
As you can see, instead of storing test1, test4, test2 in the fields under username, it is storing the index which are 0, 1, 2.
How to fix this please?
References:
#MichaelK
TABLE:
Project Table
User Table
Project-User Table
VIEW
<div class="panel-body">
<?php echo form_open('admin/add_recommended'); ?>
<div class="form-group col-lg-12">
<label>Recommended Employees:</label>
<?php echo form_error('skillsRequired'); ?>
<?php
foreach ($users as $row) {
$user[] = $row->username;
}
print_r($user);
echo form_multiselect('user[]', $user, $user, array('class' => 'chosen-select', 'multiple style' => 'width:100%;'));
?>
</div>
</div>
<div class="panel-footer">
<?php echo form_submit(array('id' => 'success-btn', 'value' => 'Submit', 'class' => 'btn')); ?>
<?php echo form_close(); ?>
</div>
CONTROLLER
public function add_recommended() {
$this->form_validation->set_rules('skillsRequired', 'Skills Required', 'min_length[1]|max_length[55]');
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
$data['users'] = $this->admin_model->getUsers($last_id);
}
$this->load->view('admin/projects/rec-employee', $data);
if ($this->form_validation->run() === FALSE) {
//$this->load->view('admin/projects/rec-employee');
} else {
$users = $this->input->post('user');
print_r($users);
foreach ($users as $user) {
$data = array(
'projectID' => $last_id,
'username' => $user
);
$id = $this->admin_model->insert('projectemp', $data);
}
if ($id) {
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_recommended');
}
}
}
RENDERED VIEW
why you use $data['users'] in controller. Where $users contains index value. You try this
//CONTROLLER
$data = $this->admin_model->getUsers($last_id); //last id is the latest id.
//VIEW
foreach ($data as $row) {
$user[] = $row->username;
}
Boy these are too many comments for a small problem.
First of all #blakcat7, I hope you won't mind If I suggest a little change in your DB Schema. Use indexes and proper normalization it always helps. I have simulated your case on my machine.
It is your user table, I have added an ID with in this table.
Its your project table, just changed some field names, you can use your own
This is your table to create your join, Although you could have used user_id or posted_by field in projects table which could solve your problem too
Now Where i see it, you have users in your database table, you also have added projects but now you want to assign or associate that project with the user.
Make it simple just create a view where you can see both projects and users
Rendered by the Controller function
public function assignProject()
{
$data['projects']=$this->admin_model->getAll('projects');
$data['users']=$this->admin_model->getAll('user');
if($_POST)
{
$this->admin_model->assignUser($_POST);
$data['success']='User Assigned';
$this->load->view('assignProjects',$data);
}
else
{
$this->load->view('assignProjects',$data);
}
}
The view rendered by following markup
<form action="" method="post">
<div class="form-group">
<label>Project</label>
<select name="project" class="form-control">
<?php for($i=0;$i<count($projects);$i++){?>
<option value="<?php echo $projects[$i]['id']?>"><?php echo $projects[$i]['title']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Users</label>
<select name="user" class="form-control">
<?php for($i=0;$i<count($users);$i++){?>
<option value="<?php echo $users[$i]['id']?>"><?php echo $users[$i]['username']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Assing User</button>
</div>
</form>
Just hit Assign User and the following function in the Model will save it in the project-user table
public function assignUser($data)
{
$record=array(
'user_id'=>$data['user'],
'project_id'=>$data['project'],
);
$this->db->insert('user_projects',$record);
}
Remember, always use an Index (ID) field in your tables, would make your DB iteration life simpler
OKAY EVERYONE, THANKS Y'ALL FOR YOUR HELP. IT REALLY MEANS SO MUCH TO ME. AFTER LIKE 2 DAYS OF STRUGGLE I FINALLY FIXED MY PROBLEM. ^_^
Special thanks to Michael K for helping me point out the problem and Malik Mudassar for giving me the idea how to do it.
Controller
public function add_recommended() {
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
}
$data['users'] = $this->admin_model->getUsers($last_id);
$this->load->view('admin/projects/rec-employee', $data);
if ($_POST) {
$users = $this->input->post('recommended');
foreach ($users as $user):
$data = array(
'projectID' => $last_id,
'userID' => $user
);
$id = $this->admin_model->insertRecEmp($data);
endforeach;
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_project');
}
}
Model
public function getUsers($id) {
$this->db->select('*');
$this->db->from('users_skills e');
$this->db->join('projects_skills p', 'e.skillsID = p.skillsID');
$this->db->join('users u', 'u.userID = e.userID');
$this->db->where('p.projectID', $id);
$this->db->group_by('e.userID');
$this->db->order_by('e.percentage', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$result[] = $row;
}
return $result;
}
return false;
}
public function getID() {
$this->db->select_max('projectID');
$this->db->from('projects');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function insertRecEmp() {
$this->db->insert('projects_users', $data);
}
View
<form action="add_recommended" method="post">
<select name="recommended[]" class="chosen-select" multiple title='Select Skills' multiple style="width: 100%;">
<?php for ($i = 0; $i < count($users); $i++) { ?>
<option value="<?php echo $users[$i]->userID ?>"><?php echo $users[$i]->username ?></option>
<?php } ?>
</select>
</form>
I completely changed my database and my PHP function for multi select

Two mysql query searches on same page?

So I have two MySql searches on my jQuery mobile page but they do not work together.
Here is the code:
my index.php code:
<?php
require "functions.php";
$posts = getAllPosts();
$posts = getSearchPosts();
?>
<?php
for( $p = 0; $p < count( $posts ); $p++ )
{
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php echo $posts[$p]["search_role"];?> <!-- using getSearchPosts -->
<?php echo $posts[$p]["search_genre"];?>
<?php echo $posts[$p]["user_first_name"];?> <!-- using getAllPosts -->
<?php echo $posts[$p]["user_last_name"];}?>
</div>
</div>
Functions.php:
function getSearchPosts()
{
require "config.php";
$posts = $c->query ( "SELECT * FROM posts" );
if ( $posts->num_rows > 0 )
{
while( $row = $posts2->fetch_assoc() )
{
$postData[] = array( "user_id" => $row[ "user_id" ], "search_role" => $row[ "search_role" ], "search_genre" => $row[ "search_genre" ] );
}
} else {
return "No Data";
}
return $postData;
}
function getAllPosts()
{
require "config.php";
$posts = $c->query ( "SELECT * FROM users" );
if ( $posts->num_rows > 0 )
{
while( $row = $posts->fetch_assoc() )
{
$postData[] = array( "user_id" => $row[ "user_id" ], "user_first_name" => $row[ "user_first_name" ], "user_last_name" => $row[ "user_last_name" ] );
}
} else {
return "No Data";
}
return $postData;
}
I assume I am to change the $posts on one function to something else such as $posts -> $search or something but it does not echo anything after changing. What can I do to have both searches done at the same time?
Do them as two separate loops. It makes no sense to show them both in the same DIVs, since there's no correspondence between the results of the two queries.
$posts = getSearchPosts();
foreach ($posts as $post) {
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php
echo $post['search_role'];
echo $post['search_genre'];
?>
</div>
</div>
<?php
}
$users = getAllPosts();
foreach ($users as $user) {
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php
echo $user['user_first_name'];
echo $post['user_last_name'];
?>
</div>
</div>
<?php
}

Can't update data using Mysql and Codeigniter

i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)

PHP link same page with link and send data via $_POST

I have a database table with (NumSection (id) and NomSection)
In my page I want display all data from 'NomSection' like a link. And when I click on the link I want open my actual page with a $_POST['nomSection'] and display data of this section.
From my page index.php :
<div>
<?php
$array = returnAllSection();
foreach ($array as $section) {
// link to same page but with a $_POST['NomSection'], For the //moment I just display it.. I don't know how do with php
echo $section['NomSection'].'<br/>';
}
?>
</div>
<div>
<?php
// here I want have $array = returnAll('NomSection) or returnAll() //if empty (this function return ALL if empty or All of a section, can I just //put returnAll($_POST[nomSection]) ?
$array = returnAll();
foreach ($array as $section) {
echo 'Titre: ' .$section['TitreArticle'].'<br/>';
echo 'Date: ' .$section['DateArticle'].'<br/>';
echo 'Texte: ' .$section['TexteArticle'].'<br/>';
echo '<br/>';
}
?>
</div>
my functions: (works good)
function returnAll($arg = 'all') {
global $connexion;
if($arg == 'all'){
$query = "select
NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection or RefSection = null;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
else {
$query = "select NumArticle,
TitreArticle,
TexteArticle,
DateArticle,
RefSection,
NomSection
from Articles, Sections where
RefSection = NumSection and NomSection = :arg;";
$prep = $connexion->prepare($query);
$prep->bindValue(':arg', $arg, PDO::PARAM_STR);
$prep->execute();
return $prep->fetchAll();
}
}
function returnAllSection() {
global $connexion;
$query = "select * from Sections;";
$prep = $connexion->prepare($query);
$prep->execute();
return $prep->fetchAll();
}
In order to post you'll need to use a form or javascript ajax post, as far as I know. Here I show a clunky form post approach that might work for what you are trying to accomplish.
<?php
function returnAllSection() {
return array(
array('NomSection' => 'foo'),
array('NomSection' => 'bar'),
array('NomSection' => 'baz'),
);
}
?>
<?php
$array = returnAllSection();
foreach ($array as $section) { ?>
<form action="" method="POST">
<button type="submit">NomSection</button>
<input type="hidden" name="NomSection" value="<?php echo htmlspecialchars($section['NomSection']); ?>">
</form>
<?php } ?>
<?php
if (isset($_POST['NomSection'])) {
error_log(print_r($_POST,1).' '.__FILE__.' '.__LINE__,0);
// do something with NomSection...
}
?>

PHP Procedural To OOP

I'm trying to convert my procedural code to oop.
<?php
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
?>
<div style="width: 100%;">
<div style="float: left;">
<?php echo $info_id; ?>
</div>
<div style="float: left;">
<?php echo $info_title; ?>
</div>
<div style="clear: both;"></div>
</div>
<?php } ?>
My incomplete attempt at classes/objects without the HTML styling:
<?php
class InfoTest {
private $info_id;
private $info_title;
public function __construct() {
$dbc = get_dbc();
$info = $dbc->query ("SELECT info_id, info_title FROM text");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
while ($info_row = $info->fetch_array())
{
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
}
$info->free();
$this->info_id = $info_id;
$this->info_title = $info_title;
}
public function setInfoID() {
$this->info_id = $info_id;
}
public function getInfoID() {
return $this->info_id;
}
public function setInfoTitle() {
$this->info_title = $info_title;
}
public function getInfoTitle() {
return $this->info_title;
}
public function __destruct() {
}
}
?>
<?php
$display = new InfoTest();
echo $display->getInfoID();
echo $display->getInfoTitle();
?>
My procedural code prints out: 1 One 2 Two.
My oop code prints out: 2 Two
From my understanding the oop prints out that way because $info_id and $info_title aren't arrays, and only print out the last stored information.
So, if I change:
$info_id = $info_row['info_id'];
$info_title = $info_row['info_title'];
To:
$info_id[] = $info_row['info_id'];
$info_title[] = $info_row['info_title'];
And print the arrays, it displays all the information I want, but how to display it in non-array form?
Is what I'm doing so far correct or am I approaching this wrong?
You're doing it wrong. In your procedural example you're iterating over the data a row at a time; in your OO example, if you treat them as arrays and then print them, you're going through the data a column at a time instead. Rather than separating the data into separate ids and titles, I would treat them as a bundle (i.e. similar to how you did it in the procedural version) - an id goes with a title, not other ids, right?
So, for example, you might have a member variable
private $texts = array();
and then in your constructor, do:
while ($info_row = $info->fetch_array()) {
$text = array(
'id' => $info_row['info_id'],
'title' => $info_row['info_title']
);
$this->texts[] = $text;
}
and then provide a method to get at this array of arrays:
public function getTexts() {
return $this->texts;
}
Finally, you could iterate over it very similarly to how you did in the procedural example:
<?php
$display = new InfoTest();
foreach ($display->getTexts() as $text) {
?>
<!-- html goes here -->
<?php echo $text['info_id']; ?>
<!-- more html -->
<?php echo $text['info_title']; ?>
<!-- other html -->
<?
}
?>
Stepping back - you could ask if all this is really necessary. There's nothing inherently wrong with procedural PHP - if it does what you need it to do and does it clearly, you might be better off favoring simple over complex here.
Because info id is an array in your object the corresponding function to get the value should take an offset. Or even better you should look at your class implementing iterator so that you can just do foreach over your object
Before switching to OOP I would first of all modularize the code and start to segment into functional parts that have separated logic from each other, e.g. database access and templating:
<?php
/**
* infos provider
*
* #return array
*/
function get_infos()
{
$infos = array();
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
while ($info_row = mysqli_fetch_array($info))
{
$infos[] = (object) $info_row;
}
return $infos;
}
foreach(get_infos() as $info)
{
?>
<div style="width: 100%;">
<div style="float: left;">
<?php echo $info->info_id; ?>
</div>
<div style="float: left;">
<?php echo $info->info_title; ?>
</div>
<div style="clear: both;"></div>
</div>
<?php } ?>
Then move the database related functions into a file of it's own to decouple it from the "templates". After that's done you can think about further steps to refactor. I suggest the following read (which is merely independent to the named framework): When flat PHP meets symfony.

Categories