I'm currently trying to fetch two images location from my database, how do I return both columns and if both empty then echo another image. This is what I've got so far.
How do I return both photo and photo_small so that I may echo them in a php file.
PUBLIC FUNCTION Profile_Pic($uiD) {
$sth = $this->db->prepare("SELECT photo,photo_small FROM users WHERE uiD = :id");
$sth->execute(array(':id' => $uiD));
if ($sth->rowCount() > 0) {
$data = $row['photo'];
return $data;
} else {
$data = './icons/users.png';
return $data;
}
}
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo'])) {
$data['photo'] = './icons/users.png';
}
if (empty($data['photo_small'])) {
$data['photo_small'] = './icons/users.png';
}
return $data;
}
if you want to replace both images if even one is absent
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo']) || empty($data['photo_small'])) {
$data['photo'] = './icons/users.png';
$data['photo_small'] = './icons/users.png';
}
return $data;
}
Just return all of the values you want in an array.
You can ensure that both photo and photo_small are not empty strings or NULL by using empty().
Don't forget to retrieve your row using PDOStatement::fetch().
You should not use rowCount() to determine the number of rows returned in a SELECT statement. According to the documentation for PDOStatement::rowCount():
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Try this:
$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row && !empty($row['photo']) && !empty($row['photo_small'])) {
$data = array('photo' => $row['photo'], 'photo_small' => $row['photo_small']);
return $data;
} else {
$data = array('photo' => './icons/users.png', 'photo_small' => './icons/users.png');
return $data;
}
Then when you call the function, your returned result can be used like this:
$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];
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]
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 am trying to get the insert id from a newly inserted row. I use the following method to query. However I am unable to get the inserted id.
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
$id = $result->insert_id; //no result, what do I put here?
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows, 'id'=>$id);
} else {
//error
return array('error'=>'Database error');
}
}
How can I modify this method to get the insert id?
$id = mysqli_insert_id($link);
This value would be called the "identity", keep that in mind when searching for information pertaining to this.
check the below links
mysql_insert_id()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html
I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.
Here is my code:
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
} else {
return $data = $query;
}
Before this code, if the code that query from database:
//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
$query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}
I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.
The script below:
//create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
$r1 = $row->rowone;
$r2 = $row->rowtwo;
$r3 = $row->rowthree;
$englishdate = $row->dob_eng;
$chinesedate = $row->dob_chi;
//add all initial data into the matrix variable for easier access to them later
$rows[0]
$rows = array(
array($r1),
array($r2),
array($r3),
array()
);
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
return ($a % $m) + 1;
}
//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
//function to access the global variable.
global $rows;
$row = $rows[$rowId];
while (sizeof($row) < $populationCount) {
$rowInd = sizeof($row) - 1;
$m = incmod($row[$rowInd], $mod);
array_push($row, $m);
}
//set the row back into the global variable.
$rows[$rowId] = $row;
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
}
I am using same query again and again on different pages in between to fetch result. I want to make a function for this query.
$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
echo $row ['name'];
How to make and how to call the function?
sample class stored sample.php
class sample
{
function getName(id)
{
$result = mysql_query("SELECT name FROM tablename where id='$id'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
}
use page include sample.php,then create object,then call getName() function.
<?php
include "db.class.php";
include "sample.php";
$ob=new sample(); //create object for smaple class
$id=12;
$name=$ob->getName($id); //call function..
?>
This is a good idea but first of all you have to create a function to run queries (as you have to run various queries way more often than a particular one)
function dbget() {
/*
easy to use yet SAFE way of handling mysql queries.
usage: dbget($mode, $query, $param1, $param2,...);
$mode - "dimension" of result:
0 - resource
1 - scalar
2 - row
3 - array of rows
every variable in the query have to be substituted with a placeholder
while the avtual variable have to be listed in the function params
in the same order as placeholders have in the query.
use %d placeholder for the integer values and %s for anything else
*/
$args = func_get_args();
if (count($args) < 2) {
trigger_error("dbget: too few arguments");
return false;
}
$mode = array_shift($args);
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if ($mode === 0) return $res;
if ($mode === 1) {
if ($row = mysql_fetch_row($res)) return $row[0];
else return NULL;
}
$a = array();
if ($mode === 2) {
if ($row = mysql_fetch_assoc($res)) return $row;
}
if ($mode === 3) {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
then you may create this particular function you are asking for
function get_name_by_id($id){
return dbget("SELECT name FROM tablename where id=%d",$id);
}
You should probably parse the database connection as well
$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function get_row_by_id($id, $database_link){
$result = mysql_query("SELECT name FROM tablename where id= '{$id}");
return mysql_fetch_array($result);
}
Usage
$row = get_row_by_id(5, $database_connection);
[EDIT]
Also it would probably help to wrap the function in a class.
function getName($id){
$result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'");
$row = mysql_fetch_array($result);
return $row ['name'];
}
call the function by
$id = 1; //id number
$name = getName($id);
echo $name; //display name