I want to create a script. The script will automatically list random firstname and lastname.
There are two database tables.
First: fake_name_id, fake_firstname
Second:fake_name_id,fake_lastname
So far I have made this:
controller file
$data['lastname'] = array();
$results = $this->getRandomLastNames();
foreach ($results as $result) {
$data['lastname'][] = array(
'lastname' => $result['lastname'],
);
}
$data['fullnames'] = array();
$results = $this->getRandomNames();
foreach ($results as $result) {
$data['fullnames'][] = array(
'firstname' => $result['firstname'],
);
}
model file >>>>> sql query firstname and lastname
public function getRandomName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_firstname FROM " . DB_PREFIX . " fakereviews_name WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'firstname' => $query->row['fake_firstname'],
);
} else {
return false;
}
}
public function getRandomNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_name ORDER BY Rand() ASC LIMIT 0, 20";
$fake_firstname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_firstname_data[$result['fake_name_id']] = $this->getRandomName($result['fake_name_id']);
}
return $fake_firstname_data;
}
public function getRandomLastName($fake_name_id) {
$query = $this->db->query("SELECT DISTINCT *, fake_lastname FROM " . DB_PREFIX . " fakereviews_lastname WHERE fake_name_id = '" . (int)$fake_name_id . "'");
if ($query->num_rows) {
return array(
'fake_name_id' => $query->row['fake_name_id'],
'lastname' => $query->row['fake_lastname'],
);
} else {
return false;
}
}
public function getRandomLastNames($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_lastname ORDER BY Rand() ASC LIMIT 0, 20";
$fake_lastname_data = array();
$query = $this->db->query($sql);
foreach ($query->rows as $result) {
$fake_lastname_data[$result['fake_name_id']] = $this->getRandomLastName($result['fake_name_id']);
}
return $fake_lastname_data;
}
twig file
{% for fullname in fullnames %}
{{ fullname['firstname'] }} {{ fullname['lastname'] }}
{% endfor %}
When the page loads. well creates 20 pieces of firstname.
But I can't get it to display lastname correctly.
Please help me to create foreach random fullname (first and last name) with predefined quantity.
You can simply use rand() function.
Create an array of fake_firstname and one for fake_lastname and then join them using a loop, wrap everything inside a function and you have what you need.
say you need an array of $n fake names
Example pseudocode:
public function randomNames($n){
// $first_name_array = fetch all first names in an array;
// $last_name_array = fetch all last names in an array;
$random_names = [];
foreach($n as $i){
$random_full_name = $first_name_array[rand(0,$n)%count($first_name_array)].' '.$last_name_array[rand(0,$n)%count($last_name_array)];
array_push($random_names,$random_full_name);
}
return($random_names);
}
Related
I am trying to execute the following query using CodeIgniter, but I am getting
Unidentified index for ->row['code'];
public function getSExtension($id) {
$temp = array();
$query = $this->db->query("SELECT extension_id FROM " . DB_PREFIX . "zipcode_shipping WHERE `zip_code` = '" . $id . "'");
if($query->num_rows) {
foreach ($query->rows as $key => $value) {
$code = $this->db->query("SELECT code FROM " . DB_PREFIX . "extension WHERE `extension_id` = '" . $value['extension_id'] . "'")->row['code'];
$this->language->load("shipping/".$code);
$temp[] = $this->language->get('text_title');
}
}
return $temp;
}
The problem is you have not correctly retrieved a result set which requires a method call. As you have it you are trying to use db properties that don't exist i.e. $query->rows should probably be $query->row_array().
Documentation Here.
In the example below I use result() and row() instead of any "array" methods.
Try this.
$temp = array();
$query = $this->db->query("SELECT extension_id FROM ".DB_PREFIX."zipcode_shipping WHERE `zip_code` = '".$id."'");
if($query->num_rows() > 0)
{
foreach($query->result() as $value)
{
$code = $this->db->query("SELECT code FROM ".DB_PREFIX."extension WHERE `extension_id` = '".$value->extension_id."'")->row()->code;
$this->language->load("shipping/".$code);
$temp[] = $this->language->get('text_title');
}
}
I am new to functional Programming, having difficulty writing a function that could fetch and output a result from a specific database table. Below is the code I've tried already.
<?php
function main()
{
$get = mysqli_query($conn, "SELECT * FROM tb_name");
if(mysqli_num_rows($get) > 0) {
$row = mysqli_fetch_array($get);
return json_encode($row);
}
}
?>
It seems not to work, Please any Idea how to get it working. Thanks :)
function select($table, $filter="", $order="", $limit="") {
$query = "SELECT * FROM " . $table . " WHERE 1 ";
if ($filter != "") {
foreach($filter as $key => $value) {
$query .= 'AND ' . $key . ' = "' . $value . '" ';
}
}
if ( $order != "" ) {
$query .= " ORDER BY ". $order;
}
if ( $limit != "" ) {
$query .= " LIMIT ". $limit;
}
return mysql_query( $query );
}
Try using:
$filter = array(
'field' => 'value'
);
$rs = select('table_name', $filter, 'id DESC', 3);
Return will be:
SELECT * FROM table_name WHERE 1 AND field = 'value' ORDER BY id DESC LIMIT 3
You can adjust the function with your needs. Use mysql_fetch_object to loop through fields results.
http://php.net/manual/pt_BR/function.mysql-fetch-object.php
Have fun http://php.net/manual/en/book.pdo.php Do some quick reading about how to connect to a database, whatever one you use (MySQL, Postgres, etc) using PDO.
Here is a simple tutorial.
I am making a script which will load all categories from a database. I just don't know how I can do this in a way which is shorter.
I am trying to figure out a way in which I can theoretically load infinite levels of categories.
$stmt1 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row1 = $db->fetch($stmt1))
{
$stmt2 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row1['Rubrieknummer'] . "'");
while($row2 = $db->fetch($stmt2))
{
$stmt3 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row2['Rubrieknummer'] . "'");
while($row3 = $db->fetch($stmt3))
{
$stmt4 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row3['Rubrieknummer'] . "'");
while($row4 = $db->fetch($stmt4))
{
$row3['CATEGORY3'][] = array(
'CATEGORY4_NAME' => ucfirst(strtolower($row4['Rubrieknaam'])),
);
}
$row2['CATEGORY3'][] = array(
'CATEGORY3_NAME' => ucfirst(strtolower($row3['Rubrieknaam'])),
'CATEGORY4' => $row2['CATEGORY4'],
);
}
$row1['CATEGORY2'][] = array(
'CATEGORY2_NAME' => ucfirst(strtolower($row2['Rubrieknaam'])),
'CATEGORY3' => $row2['CATEGORY3'],
);
}
$catagories[] = array(
'CATEGORY_NAME' => ucfirst(strtolower($row1['Rubrieknaam'])),
'CATEGORY2' => $row1['CATEGORY2'],
);
}
I would like to have some ideas on how to make this happen.
(I am using a little template system that processes the array that is being made)
EDIT:
Thanks to Ivijan Stefan Stipić I was able to solve this.
This is what I ended up doing
$categories = build_category(0);
And the function:
function build_category($parent, $row = NULL)
{
global $db;
// Initialise array
$data = array();
// Basic SQL statement
$sql = "SELECT * FROM Rubriek";
// Where condition based on $row
if(is_null($row))
{
$where = " WHERE Hoofdrubriek IS NULL";
}
else
{
$where = " WHERE Hoofdrubriek = '" . $row['Rubrieknummer'] . "'";
}
// Execute query
$stmt = $db->query($sql . $where);
// Next level parent
$next = $parent + 1;
// Fetch results
while($row = $db->fetch($stmt))
{
$data[] = array(
'CATEGORY' . $parent . '_NAME' => ucfirst(strtolower($row['Rubrieknaam'])),
'CATEGORY' . $next => build_category($next, $row),
);
}
// Return data
return $data;
}
What do you think about this solution?
function next_level($val)
{
global $db;
$stmt = $db->query("SELECT * FROM Rubriek WHERE Rubrieknummer != '" .$val. "' AND Hoofdrubriek = '" .$val. "'");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
}
$stmt = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
If I understand correctly this is the number of categories with unlimited subcategories.
I tried combining as suggested in a previous link but Im still getting a error. I am fairly new to php so that is why i have two querys.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/vhockey/public_html/vhatest/connect.php on line 88
The table is "season12" and the table is "p"
Here is my connect.php file except server info...
function index_team_stats($subconference) {
$return = array();
$query = "SELECT id, teamname, teamnameseason, teamabr
FROM teams
WHERE subconference = '" . $subconference . "'
ORDER BY teamnameseason";
$teams = result_array($query);
foreach ($teams as $team)
{
$query = "SELECT gp, w, l, ol, p
FROM season12
WHERE team = '" . $team['teamnameseason'] . "'
ORDER BY p DESC
LIMIT 0,20'; ";
$results = result_array($query);
if ($results)
{
$results[0]['team'] = str_replace($team['teamnameseason'], '', $team['teamname']);
$results[0]['teamabr'] = $team['teamabr'];
$results[0]['teamid'] = $team['id'];
$return[] = $results[0];
}
}
return $return;
}
function get_team_name($teamnameseason) {
$query = "SELECT teamname FROM teams WHERE teamnameseason = '" . $teamnameseason . "'";
$row = mysql_fetch_row(mysql_query($query));
return str_replace($teamnameseason, '', $row[0]);
}
function result_array($query) {
$results = mysql_query($query) or die("error on: " . $query . " saying: " . mysql_error());
$return = array();
while ($row = mysql_fetch_assoc($results)) {
$return[] = $row;
}
return $return;
}
Here is an image of the info ![All info sorted by team PTS from highest to lowest
Should show Penguins, FLyers, Islanders, Rangers, Devils..
Use a JOIN. An example is below. You may need to tweak based on your specific needs.
SELECT teams.id, teams.teamname, teams.teamnameseason, teams.teamabr, season12.gp,
season12.w, season12.l, season12.ol, season12.p
FROM teams, season12
INNER JOIN season12
ON teams.teamname=season12.team
WHERE teams.subconference = '$subconference'
ORDER BY season12.p
LIMIT 0,20
Please note this code is not tested and may require modification.
You can use php sort function http://php.net/usort
$callback = new function ($el1, $el2) {
if ($el1['points'] == $el2['points']) {
return 0;
}
return ($el1['points'] < $el2['points']) ? -1 : 1;
}
$sorted_result = usort($results, $callback);
I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.