Create PHP array out of table column - php

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;
}
}

Related

Remove leading column of zeros when executing a select statement to my MSSQL database

Hey guys i have microsoft sql management studio 18, where I have a database. I'm doing a select statement through php like this:
$conn = OpenCon();
$query = "SELECT id, name, picture, description, numberOfEngines FROM planes";
$result = sqlsrv_query($conn, $query);
if ($result === false) {
$status['status'] = "0";
echo json_encode($status);
}
else{
while($row = sqlsrv_fetch_array($result)) {
$theRows[] = $row;
}
echo json_encode($theRows);
}
CloseCon($conn);
and this is the output:
[{"0":1,"id":1,"1":"114","name":"114","2":"airplane1.png","picture":"airplane1.png","3":"Cessna C525","description":"Cessna C525","4":1,"numberOfEngines":1},
{"0":2,"id":2,"1":"115","name":"115","2":"airplane1.png","picture":"airplane1.png","3":"Cessna C525","description":"Cessna C525","4":1,"numberOfEngines":1},
{"0":3,"id":3,"1":"124","name":"124","2":"airplane1.png","picture":"airplane1.png","3":"Cessna C208B","description":"Cessna C208B","4":1,"numberOfEngines":1},
{"0":4,"id":4,"1":"125","name":"125","2":"airplane1.png","picture":"airplane1.png","3":"Cessna C208B","description":"Cessna C208B","4":1,"numberOfEngines":1}]
How can i remove that leading these duplicates that are showing up twice like the "0":1, or the ariplane.png.
So my output will be like this:
[{"id":1, "name":"114", "picture":"airplane1.png", "description":"Cessna C525", "numberOfEngines":1}]
To return only associative keys in your array, pass SQLSRV_FETCH_ASSOC as the fetchType parameter to sqlsrv_fetch_array:
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
This will give you an array with entries like:
{"id":1,"name":"114","picture":"airplane1.png","description":"Cessna C525","numberOfEngines":1}
If you really want the other numeric keys, keep your code as is and add
unset($row[0])
before
$theRows[] = $row;

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.

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'];
}

Something is wrong with my custom php function

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'];
}

Storing database records into array

I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// 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['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}

Categories