The code below works fine, but after running list() on the exploded sub variables ($disc1, $disc2, $disc3) I need to conditionally rename the data that's inside them.
Basically, the field 'discs' is stored in our db as a composite of acronyms (i.e., a user's CD choices are CD-DA-RD), I can separate them out but not rename. I need something like:
'CB' -> 'CLUB'
'DA' -> 'DANCE'
'RD' -> 'RADIO'
I assume I need to get $disc1, $disc2, $disc3 back into an array to do this?
Hope someone can help - thanks!
// create a function to produce the main associative array from mySQL field 'discs'
function get_user_discs($myusername) {
$discs = array();
$query = mysql_query("SELECT `discs`
FROM `members`
WHERE `email` = '{$myusername}'");
if (mysql_num_rows($query)) {
$disc = mysql_fetch_assoc($query);
}
return $discs;
}
// call the function
$temp = $_SESSION['myusername'];
$discs = get_user_discs($temp);
// explode $discs into individual parts using delimiter
list($disc1, $disc2, $disc3) = explode("-", $discs['discs'], 3);
// then rename($disc1, $disc2, $disc3) to full names....?
Related
I am building a web scraper in PHP and I am not so experimented with all this stuff. What I am trying to achieve is as following:
Split an array of values into strings using foreach
Search any value in a predefined MYSQL table. If value is identical with one of the defined ones, it should be replaced. Otherwise it should remain the same
Put the new values back into an array
Below is my snippet. Basic structure of database is "ID, Marime, Inlocuire". "Marime" is the column to search on, and "Inlocuire" is the column to replace value with.
foreach ($marimi as $marime) {
$sizes[]=trim(strtok($marime->innertext, '-'));
$newArray = array_filter($sizes, 'myFilter');
foreach ($newArray as $marimeFixa) {
$marimeDefinita = $conn->query("SELECT * FROM oc_1_tabelmarimi WHERE Marime = '$marimeFixa'");
if($marimeDefinita->num_rows == 0) {
$marimeFixa = $marimeFixa;
} else {
$marimeFixa = $marimeDefinita['Inlocuire'];
}
$arrayMarimi[] = $marimeFixa;
}
print_r($arrayMarimi);
}
However this doesn't seem to work. Any help is greatly appreciated. Thanks!
try:
$marimeDefinita = $marimeDefinita->fetch_assoc();
before if($marimeDefinita->num_rows == 0) {
or
$marimeFixa = $marimeDefinita->Inlocuire;
I have this table: TABLE_ELEMENTS, with the name ELEMENTS, i have a multiple values inside, see image.
This is the php and return the results from autocomplete request.
$("#autocomplete").autocomplete({
source: "http://localhost/include/autocomplete.php?type=mauto_complete",
First i call this..
if(isset($_GET['type']) && in_array($_GET['type'], $arr_action)) $type=$_GET['type'];
if($type == "mauto_complete") {
require_once $config_abs_path."/autocomplete/autocomplete.php";
if(isset($_GET['term'])) {
$term = escape($_GET['term']);
$response = mauto_complete::getAutocomplete($term);
echo json_encode($response);
}
}
And this is the secondauto.php file
function getAutocomplete($term) {
global $db;
global $config_table_prefix;
global $crt_lang;
$elements=$db->fetchRow("select Distinct `elements` from TABLE_ELEMENTS where `elements` like '$term%' limit 10");
$elements_array = explode("|", $elements);
return $elements_array;
}
I have write this after select
$elements_array = explode("|", $elements);
Ok the request is working fine, but in autocomplete results when i type the word Building i take no words.
But when i type the first word of the elements ( Apartment ) i take all words.
The words is not uniqe
A common approach to this is to add a | to the left of the field, then search that. This ensures that an element containing the search doesn't get matched.
select
Distinct `elements`
from
TABLE_ELEMENTS
where
lower(CONCAT('|', `elements`)) LIKE lower('%|$term%')
However, you're probably looking for something else. Below is how I'd approach it. I couldn't figure out what library you were using for your connection, so you may have to change a little bit for it to work for you.
function getAutocomplete($name, $term)
{
// make sure you escape the string to avoid SQL injection
$name = mysqli_real_escape_string($db, $name);
// make the searches case-insensitive
$term = strtolower($term);
// fetch the valid elements for the field and split them using explode
$elements = $db->fetchRow("SELECT `elements` FROM `TABLE_ELEMENTS` WHERE `name` = '$name'");
$elements_array = explode('|', $elements);
// make an array to save the matching elements
$filtered = array();
// iterate over each element to check for a match
foreach($elements_array as $element)
{
// check to see if the beginning of the element starts with the search term
if(strpos(strtolower($element), $term) === 0)
{
// add it to the filtered array
$filtered[] = $element;
}
}
// return the matching results
return $filtered;
}
Then to use it, specify what field you want to autocomplete for:
print_r(getAutocomplete('Property Type', 'B'));
// Outputs: Array
// (
// [0] => Building
// [1] => Bungalow
// [2] => Business
// )
To make your existing code to use it, change your JavaScript to match the following. You'll need to change name depending on what field you're autocompleting.
$("#autocomplete").autocomplete({
source: "http://localhost/include/autocomplete.php?type=mauto_complete&name=Property%20Type"
});
Then update the file where you call the getAutocomplete function:
if(isset($_GET['type']) && in_array($_GET['type'], $arr_action)) $type=$_GET['type'];
if($type == "mauto_complete") {
require_once $config_abs_path."/autocomplete/autocomplete.php";
if(isset($_GET['term']) && isset($_GET['name'])) {
$name = $_GET['name'];
$term = $_GET['term'];
$response = mauto_complete::getAutocomplete($name, $term);
echo json_encode($response);
}
}
Try use like this to get all possible results
$elements=$db->fetchRow("select distinct `elements` from TABLE_ELEMENTS where lower(`elements`) like lower('%$term%') limit 10");
I have a site were the user fills a form and all data is stored in a database, when the user enter his/hers page all the added data is visible. Today I´m doing this but in a lot of code rows and there is for sure a much smoother way to do this.
Here´s a look of how I have done it today:
$query = mysqli_query($dbhandle, "SELECT * FROM ..."); // ... added now
$row = mysqli_fetch_assoc($query);
$m0 = $row['m1'];
$m1 = $row['m2'];
$m2 = $row['m3'];
$m3 = $row['m4'];
...
$m47 = $row['m48'];
$firstPlace = $row['firstPlace '];
$secondPlace = $row['secondPlace '];
$thirdPlace = $row['thirdPlace '];
$fourthPlace= $row['fourthPlace'];
As you can see there are a lot of rows of code. What I would like to do is to loop through my query and then add the right value in the database to the right value in the form.
Appreciate help.
There definitely are many alternative (and in every possible sense of the word) better ways to go about your business.
For a kickoff: ask yourself what an array actually is. An array is a collection of data. You store them together because one value of that array in itself doesn't mean much. The data in an array belongs together. Why then, assign it to individual variables in the first place?
Of course, your $row array has keys like $row['m1'], which you assign to a variable called $m0. so the names of the fields in the database don't quite match the names your code uses. That's something that you can, quite easily, fix by changing your query: use aliasses for those fields:
SELECT m1 as m0, ... FROM
Now your array will have a key called m0, instead of m1. This reduces the rest of your code down to:
$row = mysqli_fetch_assoc($query);
echo 'M0: ', $row['m0'];//<-- use m0 value here.
Alternatively, you could use a second array that maps these field-names to the name you want to use in your code:
$map = array(
'm0' => 'm1'
);
echo 'M0: ', $row[$map['m0']];//use value of m0, which is the actual key if the $row array
Still, if you are hell-bound on unmaintainable, messy, error-prone and just awful code, you could use variable variables:
foreach ($row as $key => $value)
{
$$key = $val;
}
Note the double $ in $$key. This is like saying "the variable that is called whatever the value of $key is". If $key is firstname, the code above evaluates to $firstname = $value. But whatever you do: forget this is possible. It's like an enema: yes, it's possible, but you don't want one if you can avoid it. And in this case, you clearly can avoid it.
Loop through the $row var grabbing the key and value. If key starts with "m" followed by a 1 or 2 digit number, get the number, subtract one, concatenate it with "m", and assign the value. Otherwise just interpolate key into variable name and assign value.
foreach ( $row as $key => $value ) {
if ( preg_match('/^m(\d{1,2})/', $key, $matches) ) {
${'m' . ($matches[1] - 1)} = $value;
}
else { $$key = $value; }
}
In the above example, $row['m1'] value gets assigned to var $m0, and $row['firstPlace'] to var $firstPlace, etc.
How do I go about getting the most popular words from multiple content tables in PHP/MySQL.
For example, I have a table forum_post with forum post; this contains a subject and content.
Besides these I have multiple other tables with different fields which could also contain content to be analysed.
I would probably myself go fetch all the content, strip (possible) html explode the string on spaces. remove quotes and comma's etc. and just count the words which are not common by saving an array whilst running through all the words.
My main question is if someone knows of a method which might be easier or faster.
I couldn't seem to find any helpful answers about this it might be the wrong search patterns.
Somebody's already done it.
The magic you're looking for is a php function called str_word_count().
In my example code below, if you get a lot of extraneous words from this you'll need to write custom stripping to remove them. Additionally you'll want to strip all of the html tags from the words and other characters as well.
I use something similar to this for keyword generation (obviously that code is proprietary). In short we're taking provided text, we're checking the word frequency and if the words come up in order we're sorting them in an array based on priority. So the most frequent words will be first in the output. We're not counting words that only occur once.
<?php
$text = "your text.";
//Setup the array for storing word counts
$freqData = array();
foreach( str_word_count( $text, 1 ) as $words ){
// For each word found in the frequency table, increment its value by one
array_key_exists( $words, $freqData ) ? $freqData[ $words ]++ : $freqData[ $words ] = 1;
}
$list = '';
arsort($freqData);
foreach ($freqData as $word=>$count){
if ($count > 2){
$list .= "$word ";
}
}
if (empty($list)){
$list = "Not enough duplicate words for popularity contest.";
}
echo $list;
?>
I see you've accepted an answer, but I want to give you an alternative that might be more flexible in a sense: (Decide for yourself :-)) I've not tested the code, but I think you get the picture. $dbh is a PDO connection object. It's then up to you what you want to do with the resulting $words array.
<?php
$words = array();
$tableName = 'party'; //The name of the table
countWordsFromTable($words, $tableName)
$tableName = 'party2'; //The name of the table
countWordsFromTable($words, $tableName)
//Example output array:
/*
$words['word'][0] = 'happy'; //Happy from table party
$words['wordcount'][0] = 5;
$words['word'][1] = 'bulldog'; //Bulldog from table party2
$words['wordcount'][1] = 15;
$words['word'][2] = 'pokerface'; //Pokerface from table party2
$words['wordcount'][2] = 2;
*/
$maxValues = array_keys($words, max($words)); //Get all keys with indexes of max values of $words-array
$popularIndex = $maxValues[0]; //Get only one value...
$mostPopularWord = $words[$popularIndex];
function countWordsFromTable(&$words, $tableName) {
//Get all fields from specific table
$q = $dbh->prepare("DESCRIBE :tableName");
$q->execute(array(':tableName' = > $tableName));
$tableFields = $q->fetchAll(PDO::FETCH_COLUMN);
//Go through all fields and store count of words and their content in array $words
foreach($tableFields as $dbCol) {
$wordCountQuery = "SELECT :dbCol as word, LENGTH(:dbCol) - LENGTH(REPLACE(:dbCol, ' ', ''))+1 AS wordcount FROM :tableName"; //Get count and the content of words from every column in db
$q = $dbh->prepare($wordCountQuery);
$q->execute(array(':dbCol' = > $dbCol));
$wrds = $q->fetchAll(PDO::FETCH_ASSOC);
//Add result to array $words
foreach($wrds as $w) {
$words['word'][] = $w['word'];
$words['wordcount'][] = $w['wordcount'];
}
}
}
?>
I have this code above which i use to implode some variable.
The issue is that i need to create the same thing for $hostess_name[] as i did for $hostess_id_selected[].
I don't know what am i doing wrong.
I need to implode it the same way as i did with $hostess_id_selected1
foreach($hostess_id as $val) {
$hostess_id_selected[] = $val;
$sqlnomehostess="SELECT nome_hostess FROM hostess where id='$val'";
$resultnomehostess=mysql_query($sqlnomehostess)or die(mysql_error());
$hostess_name= array();
while ($row=mysql_fetch_array($resultnomehostess,MYSQL_ASSOC)) {
$hostess_name[] = $row['nome_hostess'];
}
}
$hostess_id_selected1 = implode("-",$hostess_id_selected);
you have $hostess_name= array(); inside the loop. move it above
EDIT:
some tips:
foreach($hostess_id as $val) {
$hostess_id_selected[] = $val;
// this is pointless, i mean - you are recreating $hostess_id
btw, just a little tip for improvement - instead of running many SQL queries you can use a single query:
$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list
FROM `hostess`
WHERE id IN (".implode(',',$hostess_id).")";
if the items in $hostess_id are not necessarily numeric:
$sql_ids = array();
foreach($hostess_id as $id)
$sql_ids[] = mysql_real_escape_string($id);
$sql = "SELECT GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list
FROM `hostess`
WHERE id IN (".implode(',',$sql_ids).")";
and after that:
the sql query returns 1 row with a column called "name_list", which contains the names joined with "-".
if you want to maintain the order of the id and name - you should do:
$sql = "SELECT
GROUP_CONTACT(`nome_hostess` SEPARATOR '-') AS name_list,
GROUP_CONTACT(`id` SEPARATOR '-') AS id_list
FROM `hostess`
WHERE id IN (".implode(',',$hostess_id).")";
implode is a basic function of php. It always work perfect.
Just check your array $hostess_id_selected, what it returning.
I think it will help you.