Echo out one value from an array - php

I selected an array of product IDs and product names from the table product. I tried to echo out only one product name from the array, but all I got was the first letter of the product name. Below is my code. Thanks in advance for any tips.
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];

Add brackets to the variables inside the while loop to create the array
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}
echo $productname[0];//this will print the first productname
I think is better make just 1 array of objects
$array=array();
while ($userinfo1 = $info1->fetchobject()) {
$array[] = $userinfo1;
}
echo $array[0]->productname;

instead of doing this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
while ($userinfo1 = $info1->fetchobject()) {
$productid = "$userinfo1->productid";
$productname = "$userinfo1->productname";
}
echo $productname[0];
Do this :
$info1 = $conn->prepare("SELECT `productid`,`productname` FROM `$product` WHERE id = :id ORDER BY `productname` ASC ");
$info1 ->bindParam(':id', $sessionid , PDO::PARAM_INT);
$info1->execute();
$counter =0;
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
echo $productid[counter];
echo $productname[counter];
counter++;
}
this way you'll echo out every value of the array

You have various options at your disposal. Take your look for instance, you could create an associative array like the following:
$items = array();
while ($userinfo1 = $info1->fetchobject()) {
$item = array(
'productid' => $userinfo1->$productid,
'productname' => $userinfo1->$productname
);
array_push($items, $item);
// or you could use native
// $uitems[] = $item;
}
That would give you an array ($users) that you could loop through and fetch for set index:
foreach($items as $item) {
print_r($item); // prints the whole user item.
//print $item['productid']; /* or even print the users product id.*/
}
Or simple for one item like you requested:
echo $items[0]['productid'];
Alternatively: if you'd like seperate arrays, you could do as stated in the other answers:
while ($userinfo1 = $info1->fetchobject()) {
$productid[] = "$userinfo1->productid";
$productname[] = "$userinfo1->productname";
}

Related

Is there a way I can sort this array

I want to sort a returned value from a while loop here is my code
public function Getter($stream){
$sql1 = "SELECT reg_no FROM hs_registration ";
$sql1.= "JOIN hs_students USING(reg_no) WHERE class_id = 2";
$result1 = $database->query($sql1);
$num1 = $database->num_rows($result1);
if($num1 > 0){
$records = array();
$number_of_sub = getNoSub();
while($row = mysqli_fetch_array($result1)){
//return individual score
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$records[] = number_format($flyAvg,2).' '.$row['reg_no'];
}
}
return $records;
}
$averages = Getter($stream);
foreach ($averages as $avg){
echo $avg
}
Please, I want to sort the output based on the avg with the students reg_no appended to it
Output
54.20 FMS34
91.00 FMS51
72.16 FMS64
44.81 FMS23
68.52 FMS30
48.65 FMS37
My desired output is
Output
91.00 FMS51
72.16 FMS64
68.52 FMS30
54.20 FMS34
48.65 FMS37
44.81 FMS23
If your leading numbers are always two digits, then a decimal point, the two digits, then rsort($records); would suffice.
If they might be anything else, then keep a separate sorting array, then use array_multisort() to modify the $records.
public function Getter($stream): array
{
$sql = "SELECT reg_no
FROM hs_registration
JOIN hs_students USING(reg_no)
WHERE class_id = 2";
$flyAvgs = [];
$records = [];
$number_of_sub = getNoSub();
foreach ($database->query($sql) as $row) {
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$flyAvgs[] = $flyAvg;
$records[] = number_format($flyAvg, 2) . ' ' . $row['reg_no'];
}
array_multisort($flyAvgs, SORT_DESC, $records);
return $records;
}

How to select values where another value is an array?

I'm trying to select values where another POST values are an array, I do not know what is wrong with my query giving me this error. I'm trying to know what courses are just added to table. I have five inputs in the form.
Notice: Trying to get property of non-object in C:\Apache\htdocs\xxx\addcourse.php on line 262
Here is my code
<?php
if(isset($_POST['Submit'])) {
$code= isset($_POST['code']) ? $_POST['code'] : '';
$coursecode = isset($_POST['coursecode']) ? $_POST['coursecode'] : '';
$both=$code[$x] .' '. $coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
if ($resultcourses->num_rows > 0) {
while($row = $resultcourses->fetch_assoc()) {
?>
</p>
<p> </p>
<p> </p>
<table width="415" border="0">
<tr>
<?php
$courses=$row["course_code"];
echo $courses;
?>
</div>
</tr>
</table>
<?php
}
}
}
?>
First, you build an array of the course codes that you want to retrieve; I'm leaving off the boundary checks for simplicity:
$codes = [];
foreach ($_POST['code'] as $k => $code) {
$codes[] = $code . ' ' . $_POST['coursecode'][$k];
}
Then, you prepare the statement you will use:
$stmt = $mysqli->prepare("SELECT *
FROM courses
WHERE course_code = ?
ORDER BY course_id DESC
LIMIT 5");
Followed by the main loop:
foreach ($codes as $code) {
$stmt->bind_param('s', $code);
assert($stmt->execute());
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
// ...
}
}
you can try this way with small modified code
first you have to convert string to array to get index (x) in array
$code = explode(" ", $code);
$course = explode(" ", $coursecode);
foreach ($code as $cd => $x) {
$both = $code[$x].' '.$coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
}
second you can choose variable $code or $course as length of loop based on your case
foreach ($course as $crs => $x) {
your condition...
}

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

PHP/MySQL nested fetch?

I am in the process of making a quick PHP based forum, and each post in a forum will appear under its "parent" post, but slightly more indented.
To get all the posts in that order, I have the following function:
private function getData($pid, $offset)
{
$sql = 'SELECT id, subject, date
FROM post
WHERE forum_id = ? AND parent_id = ?';
$sth = $this->db->prepare($sql);
$sth->bind_param("ii", $this->id, $pid);
$sth->bind_result($id, $subject, $date);
$sth->execute();
$data = array();
while ( $sth->fetch() )
{
$row['id'] = $id;
$row['subject'] = $subject;
$row['date'] = $date;
$row['offset'] = $offset;
//Add this 'parent' post to the data array
$data[] = $row;
//Before moving on to next post, get all its children
$data[] = $this->getData($id, $offset+1);
}
$sth->close();
return $data;
}
This isn't working because I am executing another query before closing and fetching all the data from my current statement handler.
Is there a way to maybe separate the queries so they don't conflict with each other? Or any other way to by-pass this? Or will I simply have to restructure how I get my data?
Fetch all the rows into an array, then loop over them.
$rows = array();
while ( $sth->fetch() ) {
$row['id'] = $id;
$row['subject'] = $subject;
$row['date'] = $date;
$row['offset'] = $offset;
// the cool way is $rows[] = compact('id', 'subject', 'date', 'offset');
$rows[] = $row;
}
$sth->close();
foreach ($rows as $row) {
//Add this 'parent' post to the data array
$data[] = $row;
//Before moving on to next post, get all its children
$data[] = $this->getData($id, $row['offset'] + 1);
}
I will give you a example to show how to do this, this is the table i will use for the example (after just add the forum_id):
CREATE TABLE msgs (
id INT NOT NULL AUTO_INCREMENT,
date DATETIME,
name VARCHAR(100),
message TEXT,
parent_id INT NOT NULL DEFAULT 0
);
Then, with one query do:
$query = mysql_query("SELECT * FROM msgs ORDER BY id");
Some arrays to build the "posts tree", all parent_id = 0 will be root posts:
$all_messages = array(); // Will store all messages
$root_messages = array(); // Will store only the root (or more than one if you allow)
while($row=mysql_fetch_assoc($query)){ // Main loop
$all_messages[$row['id']] = array(
'inner_messages'=>array(),
'date'=> $row['date'],
'name'=> $row['name'],
'message'=>$row['message'],
'id'=>$row['id']
);
if($row['parent_id']=='0'){ // If is a root post
$root_messages[] = &$all_messages[$row['id']];
}else{ // If not a root post, places within parent message
$all_messages[$row['parent_id']]['inner_messages'][] = &$all_messages[$row['id']];
}
}
Now to print, use a recursion:
function writeTree($msgs){
foreach($msgs as $m){
echo '<div>';
echo '<h2>'.$m['name'].' ('.$m['date'].')</h2>';
echo '<div class="text">'.$m['message'].'</div>';
writeTree($m['inner_messages']);
echo '</div>';
}
}
writeTree($root_messages);

Structure of php JSON output

this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...

Categories