This is my code
public function count_er($str_arr){
for($i=0;$i<=count($str_arr);$i++){
$counter=("SELECT COUNT(*) FROM `number` where `group_id`='$str_arr[$i]'");
$q = mysqli_query($this->con,$counter);
$row .= $q->fetch_row();
}
return $row[0];
mysqli_close($this>con);
}
}
You're better off using a single query, and using a prepared statement. Then loop over all the results and store them in an array, which you return.
public function count_er(array $str_arr) {
$result = [];
$query = "SELECT group_id, COUNT(*)
FROM `number`
WHERE `group_id` IN (".trim(str_repeat("?,", count($str_arr)), ',').")
GROUP BY `group_id`";
$stmt = $this->con->prepare($query);
// "i" for integers, "s" for strings
$stmt->bind_param(str_repeat("i", count($str_arr)), ...$str_arr);
$stmt->execute();
$stmt->bind_param($group_id, $count);
while ($stmt->fetch()) {
$result[$group_id] = $count;
}
$stmt->close();
return $result;
}
Related
I have problem connected with function returning array from sql query. The problem is that I want to return category as string and amount as float. I think the best solution is to set in while loop to write that i want category as string and amount as float. But I don't know which function can I use to make this ?
I was thinking to write something like this in while loop
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = [(string)$row['Category'],(float)$row['Amount']];
}
But there is no result, that I expected.
public static function getPieChartIncomes()
{
if (empty(Income::$this->errors)) {
$sql = "SELECT income_category_assigned_to_user_id as Category, SUM(amount) as Amount FROM incomes WHERE user_id = :userId GROUP BY income_category_assigned_to_user_id ORDER BY SUM(amount) DESC ";
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$data=array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row;
}
return $data;
}
return false;
}
public static function convertDataToChartForm($data)
{
$newData = array();
$firstLine = true;
foreach ($data as $dataRow)
{
if ($firstLine)
{
$newData[] = array_keys($dataRow);
$firstLine = false;
}
$newData[] = array_values($dataRow);
}
return $newData;
}
Finally I wanted to achieve Array for google charts like this one:
$chartIncomesArray = Income::convertDataToChartForm($incomesArray);
json_encode($chartIncomesArray) =
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
etc.
Can anybody help me with this ?
I solved my problem, deleting convertDataToChartForm($data) and changing getPieChartIncomes function to this:
public static function getPieChartIncomes()
{
if (empty(Income::$this->errors)) {
$sql = "SELECT income_category_assigned_to_user_id as Category, SUM(amount) as Amount FROM incomes WHERE user_id = :userId GROUP BY income_category_assigned_to_user_id ORDER BY SUM(amount) DESC ";
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $_SESSION['user_id'], PDO::PARAM_INT);
$i = 1;
$stmt->execute();
$tablica = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$firstLine = true;
if ($firstLine)
{
$tablica[0] = array_keys($row);
$firstLine = false;
}
$category = $row['Category'];
$amount = $row['Amount'];
$tablica[$i]=array(strval($category),floatval($amount));
$i++;
}
return $tablica;
}
Thanks to while loop like now i can get table, where array keys are strings and another rows are : category as string and amount as int like this
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
Trying to get a function working to create simple CRUD "Select" with multiple parameters to any table. I think I got the hardest part, but couldn't fetch the data right now. Maybe I'm doing something wrong I can't figure out.
My prepared statement function:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
if($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
error_log($error);
}
}
The query creator:
function create_select_query($table, $condition = "", $sort = "", $order = " ASC ", $clause = ""){
$table = escape_mysql_identifier($table);
$query = "SELECT * FROM ".$table;
if(!empty($condition)){
$query .= create_select_query_where($condition,$clause);
}
if(!empty($sort)){
$query .= " ORDER BY ".$sort." $order";
}
return $query;
}
The helper function to create the WHERE clause:
function create_select_query_where($condition,$clause){
$query = " WHERE ";
if(is_array($condition)){
$pair = array();
$size = count($condition);
$i = 0;
if($size > 1){
foreach($condition as $field => $val){
$i++;
if($size-1 == $i){
$query .= $val." = ? ".$clause. " ";
}else{
$query .= $val." = ? ";
}
}
}else{
foreach($condition as $field => $val){
$query .= $val." = ? ";
}
}
}else if(is_string($condition)){
$query .= $condition;
}else{
$query = "";
}
return $query;
}
The select function itself:
function crud_select($conn, $table, $args, $sort, $order, $clause){
$sql = create_select_query($table, array_keys($args),$sort, $order, $clause);
print_r($sql);
if($stmt = prepared_query($conn, $sql, array_values($args))){
return $stmt;
}else{
$errors [] = "Something weird happened...";
}
}
When I create the query, it seems to be OK but can't fetch the data. If I create an array with only one argument the query translates into:
SELECT * FROM `teste_table` WHERE id = ?
If I create with multiple parameters, it turns like this:
SELECT * FROM `teste_table` WHERE id = ? AND username = ?
So, how can I properly fetch the data from the select. This should be used for multiple purposes, so I could get more than one result, so the best way would be fetch data as array I guess.
I guess I'm close, but can't figure it out. Thanks
I told you to limit your select function to a simple primary key lookup. And now you opened a can of worms. As a result you are getting entangled implementation code and unreadable application code.
$table, $args, $sort, $order, $clause
What all these variables are for? How you're going to call this function - a list of gibberish SQL stubs in a random order instead of plain and simple SQL string? And how to designate a list of columns to select? How to use JOINS? SQL functions? Aliases? Why can't you just write a single SQL statement right away? You already have a function for selects, though without this barbaric error reporting code you added to it:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
Just stick to it and it will serve you all right.
$sql = "SELECT * FROM `teste_table` WHERE id = ? AND username = ?";
$stmt = prepared_query($mysqli, $sql, [$id, $name]);
$row = $stmt->get_result()->fetch_assoc();
The only specific select function could be, again, a simple primary key lookup:
function crud_find($conn, $table, $id)
{
$table = escape_mysql_identifier($table);
$sql = "SELECT * FROM $table WHERE id=?";
$stmt = prepared_query($conn, $sql, [$id], "i");
return $stmt->get_result()->fetch_assoc();
}
And for the everything else just use a generic function with native SQL.
I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}
I wrote a function that should return all users in the database. It's printing the array, but it's only printing one result. Why is it doing this? I surrounded it in a while loop and put a limit in my query...
Code:
function getAllUsers() {
global $PDO;
$stm = $PDO->prepare("SELECT * FROM `users` ORDER BY `bid` DESC LIMIT 15");
$stm->execute();
while($Array = $stm->fetch()) {
return print_r($Array);
}
}
Use fetchAll() :
$data = $stm->fetchAll()
foreach ($data as $item ) {
print_r($item);
}
use the foreach loop instead of the while and fetchAll() instead of the fetch():
foreach ($stm->fetchAll() as $arr) {
print_r($arr);
}
function getAllUsers() {
global $PDO;
$stm = $PDO->prepare("SELECT * FROM `users` ORDER BY `bid` DESC LIMIT 15");
$stm->execute();
$var = array();
while($Array = $stm->fetch()) {
$var = $Array;
}
return $var;
}
I have the following code, sorry for the length but it saves explaining most of what i need...
the $result in the pages() function is not being returned. When I call for it all I get is undefined variable. Why?
What i need is to pass the $start and $display variables to the mysql query.
<?php
if(isset($_POST['get_records_submit'])) {
$pages; $start; $display; $result;
function pages($stmt) {
//set how many records per page
$display = 10;
//determine how many pages there are
if(isset($_GET['p']) && is_numeric($_GET['p'])) { //already determined
$pages = $_GET['p'];
}
else {
$records = mysqli_stmt_num_rows($stmt);
}
//calculate the number of pages
if($records > $display) { //if there are more records than will fit on one page
$pages = ceil($records/$display); //ceil() rounds up to the nearest integer
}
else { //records will fit on one page
$pages = 1;
}
//determine which row to start returning results from
if(isset($_GET['s']) && is_numeric($_GET['S'])) { //already determined
$start = $_GET['s'];
}
else {
$start = 0;
}
$result = array(0=>$display, 1=>$pages , 2=>$start);
return $result;
}
$searchby = $_POST['search_by'];
$searchfor = $_POST['search_for'];
$contact = 1;
$i = 0;
//set the initial query
$query = "SELECT client_id, title_desc, firstname, surname, house, street, town, city, county, postcode as count FROM address LEFT JOIN client USING (client_id) LEFT JOIN client_title USING (title_id) LEFT JOIN address_street USING (address_id) LEFT JOIN address_town USING (address_id) LEFT JOIN address_city USING (address_id) LEFT JOIN address_county USING (address_id) WHERE is_contact = ?";
//depending on search terms, amend the query
if($searchby == 'all') {
$query .= " ORDER BY surname ASC, firstname ASC";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, 'i', $contact);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
pages($stmt);
var_dump ($result);
foreach ($result as $var) { echo $var.' ';}
mysqli_stmt_close($stmt);
$query .= " ORDER BY surname ASC, firstname ASC LIMIT ?, ?";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, 'iii', $contact, $start, $display);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $client_id, $stitle, $sfname, $ssname, $shouse,$sstreet, $stown, $scity, $scounty, $spostcode);
if($searchfor != '') {
echo "<p>You searched under <span class=\"bold\">\"All\"</span>, therefore your search term <span class=\"bold\">\"$searchfor\"</span> has not been included.</p>";
}
}
}
In this line:
pages($stmt);
The function pages() returns the array, but this result is not being set to a variable. Try using:
$result = pages($stmt);
And then accessing the array via the variable $result.
That $result variable that you declared up top? The reason it's not being set is because the function pages() doesn't have access to it because it's not within the function's scope.
Edit
As Lyth pointed out, if you don't want the function to return anything, you can modify your function as follows:
function pages($stmt) {
global $result;
// ...
// The rest of your function
// ...
$result = array(0=>$display, 1=>$pages , 2=>$start);
// Remove the 'return $result' line
}
I do not know why you write $pages; $start; $display; $result;? If you want to get the value of array try to use this...
$result = array($display, $pages , $start);
return $result;
You can check the array with
print_r ($result);