Something is wrong with my custom php function - php

Okay so I am trying to create a custom function that will echo a site url inside an iframe for the end user.
The script has to check whether or not the user has already seen the site and if they have seen it don't display it any more, but take another site url from the database etc.
Here's what I have come up with so far:
function get_urls() {
require 'config.php';
global $con;
global $currentUsername;
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
$query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL";
$result = mysqli_query($con, $query);
// Get all the site urls into one array
$siteUrls = array();
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
$query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL";
$result2 = mysqli_query($con, $query2);
// Get urls the user has already seen into another array
$seenUrls = array();
$index = 0;
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
// Compare the two arrays and create yet another array of urls to actually show
$urlsToShow = array_diff($siteUrls, $seenUrls);
if (!empty($urlsToShow)) {
// Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site
foreach ($urlsToShow as $urlToShow) {
echo $urlToShow;
$query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
mysqli_query($con, $query);
break;
}
}
// Show the allSeen file when all the ads are seen
else {echo 'includes/allSeen.php';}
mysqli_free_result($result);
mysqli_close($con);
}
I have currently found two errors with this. First the $siteUrls and $seenUrls are all okay, but when I compare the two using array_diff then it returns an empty array.
Secondly the script doesn't write the site url into the database because the $urlToShow is an array not a single url?

I think the problem is in your code is at the place where you are creating your $siteUrls, $seenUrls arrays. mysqli_fetch_assoc() function will give you a result row as an associative array. So if you want to change some of your code in the while loops.
Please chnage this
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row;
$index++;
}
To
while($row = mysqli_fetch_assoc($result)) {
$siteUrls[$index] = $row['site_url'];
$index++;
}
And in the second while loop also. Change this
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2;
$index++;
}
To
while($row2 = mysqli_fetch_assoc($result2)) {
$seenUrls[$index] = $row2['site_url'];
$index++;
}
and try

i would not run two queries and try to merge the result array. you can use mysql itself to just return the sites that have not been seen yet:
SELECT sites.site_url FROM sites
LEFT JOIN views ON views.site_url=sites.site_url AND views.user='$currentUsername'
WHERE sites.site_url IS NOT NULL AND views.site_url IS NULL
This will return only site_urls from sites, that have no entry in the views table. The LEFT JOIN will join the two tables and for every non-matching row there will be NULL values in the views.site_url, so that is why i am checking for IS NULL.
Your saving of $urlToShow should work, if you set to $row field content and not $row itself as suggested, but if you want to check what is in the variable, don't use echo use this:
print_r($urlToShow);
If the variable is an array, you will see it's content then.

#Azeez Kallayi - you don't need to index array manually.
$seenUrls[] = $row2['site_url'];
In addition, you can fetch all result
$rows = mysqli_fetch_all($result2,MYSQLI_ASSOC);
foreach($rows as $row){
echo $row['site_url'];
}

Related

Storing database results to a variable in PHP

I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]

echoing a result from the database with php only returns 1 result

I'm trying to get results from a database and return the data to my page.
I have 2 files, findtask, and functions.
In functions I have some code that grabs all my data from the table.
I then used a while loop to grab the stuff if I echo the results from the functions script it returns as it should id 1 2 and 3, my issue starts when trying to get the result from findtask script that only gets last result.
<?php
public function ShowOpenTasks ()
{
//i leave usersemail blank, because i only want tasks to show on this page if there not assigned.
$query = "SELECT * FROM `tasks` WHERE `usersemail` = ''";
if(!$result = mysqli_query($this->db, $query)) {
exit(mysqli_error($this->db));
}
$data = [];
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$data = $row;
echo $data['id'];
}
}
return $data;
}
?>
My findtask page is
require __DIR__ . '/lib/functions.php';
$app = new FunctionClass();
$task = $app->ShowOpenTasks();
echo $task['id'] //id being the name of the id table of the task.
This one will only turn the last id for some reason.
What is wrong and how can this be fixed?
It will only return last id since you are setting data to equal row
$data = $row;
So each row you replace it with the last one.
I guess you want an array instead, so you could do:
$data[] = $row;
then to print out all tasks:
$task = $app->ShowOpenTasks();
print_r($task);
This would give you an array of results.

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Categories