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.
Related
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);
}
Some rows are being printed out multiple times, the variable $foo shows that its the foreach($students as $student) loop but I just can't figure out why it's happening.
This is a custom report in Moodle
Here's my code
require_once('../../config.php');
require_once($CFG->libdir . '/adminlib.php');
admin_externalpage_setup('reportlink_critic', '', null, '', array('pagelayout'=>'report'));
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('pluginname', 'report_link_critic'));
$table = new html_table();
$table->head = array('Student', 'Links Posted', 'Votes Received', 'Cumalative Score', 'Rating', 'Foo');
$table->headspan = array(1, 1, 1, 1, 1, 1);
$query_students = "SELECT id, firstname, lastname FROM mdl_user WHERE confirmed = '1' AND deleted = '0'";
$students = $DB->get_recordset_sql($query_students);
$foo = 1;
foreach( $students as $student ) {
$query_links = "SELECT count(id), user_id AS links_posted FROM mdl_link_critic_links WHERE user_id = '" . $student->id . "'";
$links = $DB->get_recordset_sql($query_links);
foreach($links as $link) {
$links_posted = $link->links_posted;
}
$query_votes = "SELECT count(v.id) AS votes FROM mdl_link_critic_votes v JOIN mdl_link_critic_links l ON l.id = v.link_id WHERE l.user_id = '" . $student->id . "' ";
$votes = $DB->get_recordset_sql($query_votes);
foreach($votes as $vote) {
$total_votes = $vote->votes;
}
$query_scores = "SELECT sum(v.vote_score) as score FROM mdl_link_critic_votes v WHERE user_id = '" . $student->id . "' ";
$scores = $DB->get_recordset_sql($query_scores);
foreach($scores as $score) {
$cumalative_score = $score->score;
}
$foo = $foo + 1;
if($links_posted > 0) {
$rating = round(($total_votes * $cumalative_score) / $links_posted, 2);
$cells = array( $student->firstname . ' ' . $student->lastname, $links_posted, $total_votes, $cumalative_score, $rating, $foo );
}
if(!empty($cells)) {
$table->data[] = new html_table_row($cells);
}
}
echo html_writer::table($table);
$students->close();
$links->close();
$votes->close();
$scores->close();
echo $OUTPUT->footer();
The report prints out each row as student name, votes received, cumalative score, Rating and my count of $foo, but some students are printed out several times ? Very confused
I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.
use query for access the $current_rank this value want to access in different query but this value can not access any where in different query so how to access $current_rank......
$query = "select * from menu_master where menu_id =
$row_id and hotel_id='" . $_REQUEST['hotel_id'] . "'";
$result = mysql_query($query)."<br/>";
while($row=mysql_fetch_array($result))
{
$rank = $row['set_rank'];
}
$current_rank = $rank;
//echo $current_id = $row_id."<br/>";
//echo $new_rank =$_REQUEST['set_rank']."<br/>";
$sql = "select * from menu_master where set_rank = '$new_rank ' and hotel_id='".$_REQUEST['hotel_id']."'" ;
// echo $sql."<br/>";
$rs = mysql_query($sql)."<br/>";
while($row = mysql_fetch_array($rs))
{
$menu_id = $row['menu_id'];
$sql="update menu_master
set set_rank=$current_rank where menu_id= $menu_id and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
mysql_query($sql)."<br/>";
}
$sql="update menu_master set menu_name = '" . mysql_real_escape_string($_REQUEST['menu_name']) . "',
menu_name_ar = '" . mysql_real_escape_string($_REQUEST['menu_name_ar']) . "',
is_active = '" . $is_active . "',
set_rank = $new_rank where menu_id = '$current_id' and hotel_id='".$_REQUEST['hotel_id']."'";
//echo $sql."<br/>";
//exit;
mysql_query($sql);
Your current_rank seems to be an array. If you have single value in current_rank, then do not use while loop for it.
Just use $row=mysql_fetch_array($result);
$current_rank = $row['set_rank'];
Also you have commented out this line.
//echo $new_rank =$_REQUEST['set_rank']."";
So you have no value for $new_rank
OK I know this should be easy but i'm going round in circles. I have two tables, and two functions each running a query, the first function gets a product, the second one gets images for a product
I want to get an array which is the product, and it's images...
here's my code...
/**
* Gets the requested product from the DB
*
* #param string $productUrl
* #param string $productID
*/
private function _db_get_product($productUrl = null, $productID = null) {
if (empty($productUrl) && empty($productID))
return;
$db = $this->getConnection();
$q = "SELECT " . $this->_leaf_sql_fields() .
" FROM content_products_items pr WHERE pr.productStatus >= "
. menuMachine::getMinimumStatus() . " ";
if (!empty($productUrl))
$q .= " AND productUrl = '" . $productUrl . "'";
if (!empty($productID))
$q .= " AND productID = '" . $productID . "'";
if ($res = $db->recordsetSingle($q))
$this->_product = $res;
return $res;
}
/**
* Get the images for the product
* #return array
*/
private function _db_get_product_images($productID) {
$db = $this->getConnection();
$q = "SELECT * FROM content_products_images WHERE productID = '" . $productID . "'";
$this->_productImages = $db->recordset($q);
}
Are you just looking for a query to combine the two within the same function?
//Basic query, improve it according to your needs
SELECT
*
FROM
content_products_items as p,
content_products_images as i
WHERE
p.productID = $productId AND
i.productID = p.productID;
Or for a way to call both functions and combine the results in a array?
$myProduct = array(
'productData' => $this->_db_get_product($productUrl, $productID),
'productImages' => $this->_db_get_product_images($productID),
);
Both should guide you into a working direction.
My first attempt at answering someone here on StackOverflow, so bear with me ... but I think the below is what you are looking for?
$product = array('product' => _db_get_product($URL, $ID), 'images' => _db_get_product_images($ID));
Alternately, if you want it all in one go and don't need the two separate methods for anything else, you could rewrite your _db_get_product method as follows:
private function _db_get_product($productUrl = null, $productID = null) {
if (empty($productUrl) && empty($productID))
return;
$output = array();
$db = $this->getConnection();
$q = "SELECT " . $this->_leaf_sql_fields() .
" FROM content_products_items pr WHERE pr.productStatus >= "
. menuMachine::getMinimumStatus() . " ";
if (!empty($productUrl))
$q .= " AND productUrl = '" . $productUrl . "'";
if (!empty($productID))
$q .= " AND productID = '" . $productID . "'";
if ($res = $db->recordsetSingle($q))
array_push($output, $res);
$q2 = "SELECT * FROM content_products_images WHERE productID = '" . $productID . "'";
array_push($output, $db->recordset($q2));
return $output;
}