Codeigniter + MySQL - Search containing string - mysql

I have column in table of database with value: PL TOFLEX NEGRO/PRETO
I search in my website: TOFLEX PRETO
I need output: PL TOFLEX NEGRO/PRETO
Can someone give me correct query to do this?
I try:
public function searchMaterial($nome)
{
$json = [];
$this->load->database();
if(!empty($this->input->get("q"))){
$this->db->like('nomeMaterial', $nome, 'both');
$query = $this->db->select('idMaterial as id,nomeMaterial as text')
->limit(50)
->get("material");
$json = $query->result();
}
echo json_encode($json);
}
but doesn't work.

You have to split your terms before querying your database.
I assume nomeMaterial is the name of your column.
Try this if you want your column contains BOTH terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->like('nomeMaterial', $term);
}
Or try this if you want your columns contains at least one of the terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->or_like('nomeMaterial', $term);
}

Related

Unique Profile Slug with PHP and PDO

I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL

Codeigniter Array values Assign to Variables

I have following data array returned by Item_model. This array included some values of MySQL tables columns such as 'r_qty' and 'ap_qty'.
$this->data['issueData']=$this->Item_model->ItemRequestfromHDData($id);
Item_model
function ItemRequestfromHDData($id)
{
$this->db->select('store_update_stock.*,store_update_stock_details.*,tbl_user.username,store_item.*,
sum(qty) as avqty, sum(store_update_stock_details.r_qty) as r_qty,
sum(store_update_stock_details.ap_qty) as ap_qty');
$this->db->from('store_update_stock_details');
$this->db->join('store_update_stock', 'store_update_stock.update_stock_id=store_update_stock_details.update_stock_id');
$this->db->join('tbl_user', 'store_update_stock.supplier=tbl_user.userId');
$this->db->join('store_item', 'store_update_stock_details.item=store_item.item_id', 'left');
$this->db->where(array('store_update_stock.update_stock_id' => $id, 'store_update_stock_details.status' => 1));
$this->db->group_by('store_item.item_id');
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
I want to assign these two columns / values to variables. I tried following assignments.
$r_qty = $data['r_qty'];
$ap_qty = $data['ap_qty'];
but didn't get the expected result. What may be going wrong ? Can anyone help ?
As per codeigniter documentation,
result()
This method returns the query result as an array of objects, or an
empty array on failure.
Typically you’ll use this in a foreach loop, like this:
$query = $this->db->query("YOUR Q enter code here QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
So, your code should be
foreach ($this->data['issueData'] as $data)
{
$r_qty = $data->r_qty;
$ap_qty = $data->ap_qty;
}

Function returns 1 instead of result (PDO)

I have a function which is printed below. THis is meant to dynamicly draw user data from the database using PDO (that situation is clear and all works well). But, instead of returning the result (i e. an email for you("email)), it returns the number 1.
Here's my setup:
public function you($row) {
if(isset($_COOKIE["SK"])) {
$pw = $this->baseXencode($_SESSION["password"]);
$usr = $this->baseXencode($_SESSION["username"]);
$q = "SELECT $row FROM SN_users WHERE username=':USR' AND password=':PW'";
$this->netCore->q($q);
$this->netCore->bind(":PW", $pw);
$this->netCore->bind(":USR", $usr);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
} else {
$q = "SELECT $row FROM SN_users WHERE username='Anonymous' AND password='Anonymous'";
$this->netCore->q($q);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
}
}
}
$this->netCore->q() = PDO query
$this->netCore->single() PDO fetch(PDO::FETCH_ASSOC)
As for ->bind, self-explanatory.
Please help, will be very much appreciated.^^
When using parametrized queries, you don't put the parameters in quotes. That prevents the parameters from being substituted, since it's treated as a literal string. So it should be:
$q = "SELECT $row FROM SN_users WHERE username=:USR AND password=:PW";
I'm surprised it's returning 1. I'd expect your code to cause an error, because single() should be returning false, and false[$row] is not valid.
You should also check that a row was returned; if the username and password are not valid, you won't get an result. So it should be:
$result = $this->netCore->single();
if ($result) {
return $result[$row];
} else {
return false;
}
And the caller of you() needs to check the value as well.

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.

JSON encode comma delimited row

I'm trying to add an autocomplete tokenizer script to some form fields and one issue I'm having is if a person saves multiple values for the field the autocomplete suggestions come back with all of his values as one long value instead of them being single values delimited by the comma. I first tried to simply explode the value but it doesn't format it correctly in the JSON encode.
Here is my PHP file:
//connection information
$host = "localhost";
$user = "myuser";
$password = "mypass";
$database = "mydb";
$param = ($_GET["term"]);
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'");
//build array of results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$activities[$x] = array(cb_activitiesterm => $row[cb_activities]);
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($activities) . ")";
echo $response;
mysql_close($server);
This gives the output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,hockey,"}]
but I need it to output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,"},"cb_activities":"hockey,"}]
I also need to find a way to prevent duplicate entries from populating. For instance, the way it is now, say 10 people all have kicking cats selected as a value, it will display 10 times in the autocomplete suggestions.
How do I set this up to correctly delimit at the commas and then weed out duplicate values?
NM the duplicate issue, I just added select distinct instead of just select, this json thing has me overcomplicating things now lol. Now if I can just figure out how to delimit properly at the comma all will be good.