PHP - How To Return An Entire Array From A Php Function?
I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake Similar TutorialsHi,Dear Frnds...........................I Hope U r all fine. I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... My tree gather function gives me multidimensional array. However i want it to be one dimensional . I was getting one dimensional earlier however i forgot how i got it. Can someone please tell me my mistake Code Code: [Select] <?php include'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $eh[] = tree_gather($array['lchild']); $child = array_merge($child, $eh); $eh1[] = tree_gather($array['rchild']); $child = array_merge($child, $eh1); } return $child; } $pair = tree_gather(1000000); echo "<pre>"; print_r($pair); echo "</pre>"; ?> Output Code: [Select] Array ( [0] => 3632873 [1] => 5951538 [2] => Array ( [0] => 8930480 [1] => 7563232 [2] => Array ( [0] => 1144744 [1] => 4386810 [2] => [3] => ) [3] => ) [3] => ) I'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } I've used a lot of solutions from this site, however, this is my first post, so go easy on me :-) I've created a product form the successfully INSERTS data to a mysql table. I can successfully query the data so that product information can be updated. When I click submit to UPDATE the rows, everything updates except for 2 fields that are arrays. Here is my product form that populates data to be edited. Code: [Select] <?php session_start(); require("config.php"); require("db.php"); require("functions.php"); if(isset($_SESSION['SESS_ADMINLOGGEDIN']) == FALSE) { header("Location: " . $config_basedir); } if(isset($_GET['func']) == TRUE) { if($_GET['func'] != "conf") { header("Location: " . $config_basedir); } $validid = pf_validate_number($_GET['id'], "redirect", $config_basedir); header("Location: " . $config_basedir . "adminedit.php"); } else { require("header.php"); $sql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";"; $query = mysql_query($sql); while ($prodrow = mysql_fetch_array($query)){ $id = $prodrow['id']; $active=$prodrow['active']; $cat_id=$prodrow['cat_id']; $name=$prodrow['name']; $description=$prodrow['description']; $details=$prodrow['details']; $price=$prodrow['price']; $price2=$prodrow['price2']; $price3=$prodrow['price3']; $price4=$prodrow['price4']; $price5=$prodrow['price5']; $price6=$prodrow['price6']; $minimum=$prodrow['minimum']; $price7=$prodrow['price7']; $price8=$prodrow['price8']; $price9=$prodrow['price9']; $image=$prodrow['image']; } ?> <form action="adminprodupdate.php" method="post"> <table width="500" border="1" cellpadding="10"> <tr> <td>ID:</td> <td><input type="hidden" value="<? echo $id; ?>" name="id" /></td> </tr> <tr> <td>Active:</td> <td><input name="active" type="radio" value="0" <?php echo ($active=='0')? 'checked':'';?> />Yes<br /> <input name="active" type="radio" value="1" <?php echo ($active=='1')? 'checked':'';?> />No</td> </tr> <tr> <td>Category:</td> <td><input name="cat_id" type="radio" value="1" <?php echo ($cat_id=='1')? 'checked':'';?> />Hats<br /> <input name="cat_id" type="radio" value="2" <?php echo ($cat_id=='2')? 'checked':'';?> />Shirts<br /> <input name="cat_id" type="radio" value="3" <?php echo ($cat_id=='3')? 'checked':'';?> />Promotional Items</td> </tr> <tr> <td>Product ID: </td> <td><input type="text" name="name" value="<? echo $name; ?>"></td> </tr> <tr> <td>Short Description: </td> <td><input type="text" name="description" value="<? echo $description; ?>"></td> </tr> <tr> <td>Details:</td> <td><textarea name="details" cols="50" rows="10" ><? echo $details; ?></textarea></td> </tr> <tr> <td>Price for S-XL:<br /> <br /><strong><div id="redfont">**Shirts**<br />&<br />**Hats**</div></strong></td> <td>1-23: <input type="text" name="price" value="<? echo $price; ?>"><br><br> 24-47: <input type="text" name="price2" value="<? echo $price2; ?>"><br><br> 48+: <input type="text" name="price3" value="<? echo $price3; ?>"><br><br> </td> </tr> <tr> <td>Price for 2XL - 5XL:<br /> <br /><strong><div id="redfont">**Shirts ONLY!**</div></strong></td> <td>1-23: <input type="text" name="price4" value="<? echo $price4; ?>"><br><br> 24-47: <input type="text" name="price5" value="<? echo $price5; ?>"><br><br> 48+: <input type="text" name="price6" value="<? echo $price6; ?>"><br><br> </td> </tr> <tr> <td>Minimum QTY: </td> <td><input type="text" name="minimum" value="<? echo $minimum; ?>"></td> </tr> <tr> <td>Sizes:</td> <td><? echo ''; $result = mysql_query("SELECT * FROM sizes"); while ($row = mysql_fetch_assoc($result)) { $selected = ''; $result2 = mysql_query("SELECT * FROM productoptions WHERE productid = '" . $_GET['id'] . "' AND sizeid = '" . $row['id'] . "'"); if ($row2 = mysql_fetch_assoc($result2)) { $selected = 'checked '; } echo '<input type="checkbox" name="size[]" value="' . $row['id'] . '" ' . $selected . '/> ' . $row['size'] . '<br />'; } ?> </td> </tr> <tr> <td>Colors:</td> <td><? $result = mysql_query("SELECT * FROM colors"); while ($row = mysql_fetch_assoc($result)) { $selected = ''; $result2 = mysql_query("SELECT * FROM productoptions WHERE productid = '" . $_GET['id'] . "' AND colorid = '" . $row['id'] . "'"); if ($row2 = mysql_fetch_assoc($result2)) { $selected = 'checked '; } echo '<input type="checkbox" name="color[]" value="' . $row['id'] . '" ' . $selected . '/> ' . $row['color'] . '<br />'; } ?> </td> </tr> <tr> <td> </td> <td><input type="Submit" value="Update this product"></td> </tr> </form> </table> <?php } require("footer.php"); ?> Here is my script: Code: [Select] <?php include("config.php"); include("db.php"); $id=$_POST['id']; $active=$_POST['active']; $cat_id=$_POST['cat_id']; $name=$_POST['name']; $description=$_POST['description']; $details=$_POST['details']; $price=$_POST['price']; $price2=$_POST['price2']; $price3=$_POST['price3']; $price4=$_POST['price4']; $price5=$_POST['price5']; $price6=$_POST['price6']; $minimum=$_POST['minimum']; $arrsizes = $_POST['size']; $arrcolors = $_POST['color']; $image=$_POST['image']; $sql="UPDATE products SET active = '$active', cat_id = '$cat_id', name = '$name', description = '$description', details = '$details', price = '$price', price2 = '$price2', price3 = '$price3', price4 = '$price4', price5 = '$price5', price6 = '$price6', minimum = '$minimum', image = '$image' WHERE id = '$id'"; $result = mysql_query("SELECT id FROM products ORDER BY id DESC LIMIT 0,1"); if ($row = mysql_fetch_assoc($result)) { $productid = $row['id']; } foreach ($arrsizes as $sizevalue) { foreach ($arrcolors as $colorvalue) { $sql2="UPDATE productoptions SET sizeid = '$sizevalue', colorid = '$colorvalue' WHERE productid='$id' "; } } mysql_query($sql) or die ("Error: ".mysql_error()); mysql_query($sql2) or die ("Error: ".mysql_error()); echo $sql; echo $sql2; header("Location: " . $config_basedir . "adminhome.php"); ?> And here is what is echo'd after submit: Code: [Select] UPDATE products SET active = '0', cat_id = '2', name = 'Test Edit Prod', description = 'just a simple test', details = 'just a simple testjust a simple testjust a simple testjust a simple testjust a simple testjust a simple test', price = '1', price2 = '2', price3 = '3', price4 = '4', price5 = '5', price6 = '6', minimum = '127', image = '' WHERE id = '41'UPDATE productoptions SET sizeid = '6', colorid = '5' WHERE productid='41' This part of the code: UPDATE productoptions SET sizeid = '6', colorid = '5' WHERE productid='41' , is supposed to be updating sizes and colors, however, it is only updating the last size/color selected in the check box. Thanks in advance for any support! I have an array containing webpages. $results = array(www.google.com, www.phpfreaks.com); echo file_get_contents($results[0]); echo file_get_contents($results[1]); Is there anyway to just echo get_file_contents without putting in the position in the array as I have hundreds of variables in it? Ok so here's what I'm trying to do and what I'm having to do since I can not figure out how to script this.
I create my GUI for scripting in HTML. When I script I create a full HTML page for my input forms, one full HTML page for the error code and lastly one HTML page for the receipt when the script runs correct. I then create my php scripting (basic template where I can cut and paste my HTML for the GUI output once it has been encapsulated in FULL be the php print function after having the quotation marks escaped and replaced by a backslash follow by a quotation mark).
Currently and over the past Decade. I have done this encapsulation the Hard way. Meaning I build my HTML file in FrontPage. I save the HTML file and then I open it in Microsoft Notepad. First thing I do is use the replace All function from the edit menu to Find every instance of " and replace them all with \" then I manually goto the first line of code and place a Tad then type print " I then hold control and shift to copy the ( tab print ") and begin to paste manually using Ctrl V and then I hit the down arrow on my keyboard quickly followed by the Home button to drop my cursor down a line and input the beginning of my PHP print function encapsulation one frigging line at a time. Once I've reach the very bottom, I go up the back right hand side of the HTML document with my ending quotation followed by semi colon manually with Ctrl V and hitting up arrow followed by end button.
This process of encapsulation the hard way with note pad takes up 90% of my dev time when programming. It makes stuff easy to read in my code and is perfect for outputting. What I would like to do is find a way to create a php script with a file upload form field that would take the input of any and all html files and parse the full document automating the exact process that I run on all of my HTML GUI files so that I can turn the encapsulation work into nothing and focus on the actual scripting.
You wouldn't believe how many hours of Ctrl V and up n down end and home I have pressed. Spent 8 hours last night alone. When form fields have multiple drop down selectors for country code ect. the HTML files to encapsulate manually become Ridiculously long.
I have never seen or heard of anyone doing exactly what I've explained here as I know the print function used like this is not normal. Every HTML file or snippet in any of my scripting is always encapsulated in the print function to output. And I have no intentions on changing my style. I would like to automate my process. And if it is too complex for me to build it in a decent amount of time I am willing to pay good money to get this finished for me ASAP.
Please message me back ASAP as I'm working on a personal project that has over 2,000 HTML files for me to encapsulate a the minimum.
~PJ
Hi all, can you give me suggestion how to return value from function like this Code: [Select] function returnArray(){ for($i=1; $i<=3; $i++){ return $i; //how to return this as array?? } } when I code "echo" inside the function then call the function it give me output => 123 but when I code "return" inside the function, it will give output => 1 Can you suggest me how to output it as array? let say i have a function function checkme($x) { if(strlen($x)>10) { return $x; } else { return false; } } $variable=checkme("5"); so two questions i wish to ask... 1. If i wish to get the empty string for the $variable, then is it correct to have return false there? 2. If it is true that return shall not be used twice in a function as it will somehow reduce bytes space or something like that?? thanks in advance Hi, i got this function to get the wordCount that i store in a tabel: Code: [Select] function getWordCount($word) { $query = "SELECT count FROM uniqueWords WHERE word='$word'"; $data = execQuery($query); return $data; } Only it returns an array, what i want is to have it return a integer, how can i do that? Hi everyone for my end of studies projects I decided to do a little e-commerce problem on the filter .. I use an ajax request at the click of the checkbox this goes to my controller which calls a method of my Model class but the concern is that .. if the array $ _POST ['brands'] has several elements then only the last one is returned to me? I thought I saw one day that if the same variable is in a url then the last value will be returned to me is for security but how can I do ... I have been there for too long .. and finally despair. . Help me please... :') request payload: brands%5B%5D=arai&brands%5B%5D=bell reply :
<- prepare var_dump ()
string (4) "arai" <- bind
var_dump () of my fetchAll () since the last value taken into account is bell then I get two items of the bell brand from my bdd but no arai ... Edited October 24, 2020 by jcb789error Hi, I have some strange issues with my code: Code: [Select] <?PHP session_start(); $loginid = $_SESSION["valid_id"]; // First check if we are guest or user. if (!$_SESSION["valid_email"]) { $visitor = "yes"; } else { $visitor = "no"; $email = $_SESSION['valid_email']; $userid = $_SESSION['valid_id']; } //Load Header (blue menu) require("./inc/header.php"); //Load Sub-acc (silver account menu) require("./inc/sub-group.php"); //Load nav-group (Tabs) require("./inc/nav-group.php"); //Load Config file require("./inc/config.php"); //Set & get profile ID $getid = $_GET["id"]; //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); } //If we are guest, do we allow anon access to the profile IF ($row["privacy"] <= 10 && $visitor = "yes") { exit("You may not view this profile as a visitor, due to the users privacy settings"); } //Let's check if we are friends ELSEIF ($visitor = "no") { $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); $row2 = mysql_fetch_array($result2); $friends = $row2["status"]; if (mysql_num_rows($result2) = 0) { $friends = "no"; } } //If we are friend, do we allow access to the profile IF ($row["privacy"] >= 9 && $friends != 1) { exit("You may not view this profile because of the privacy settings."); } $row = mysql_fetch_array($result); $memgroup = $row["group"]; IF ($row["activated"] != 1) { exit("This account is suspended and cannot be viewed."); } //Check what group member is in. $result2 = mysql_query("SELECT * FROM profiles_groups WHERE id=('$memgroup') LIMIT 1"); $row2 = mysql_fetch_array($result); ?> Alright, so the error: Fatal error: Can't use function return value in write context in C:\xampp\htdocs\prog\profile.php on line 45 Code: [Select] 42. $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); 43. $row2 = mysql_fetch_array($result2); 44. $friends = $row2["status"]; 45. if (mysql_num_rows($result2) = 0) Alright, this is one thing that bothers me, the other is: Code: [Select] //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); I tried to put an invalid ID, and already here the script should have died/exited before executing the parts of the code that doesn't work. I tested my code on another page and it works flawlessly, perhaps this error is just generated before it actually exists i dunno.. Any way, any help is much appreciated } not sure if this is possible but i do not know how to return multiple values and read them where the call was made. Code: [Select] $string = "clause1"; func1($string); // somehow read the response and use the return values seperately. // both $string2 and $string3 Code: [Select] function func1($input) { if ($input == "clause1") { $string2= "value2"; $string3= "value6"; } if ($input == "clause2") { $string2= "value3"; $string3= "value7"; } if ($input == "clause3") { $string2= "value4"; $string3= "value8"; } if ($input == "clause4") { $string2= "value5"; $string3= "value9"; } return ($requesttype, $messagetitle); } Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! This is my error: Code: [Select] Fatal error: Can't use function return value in write context in /home/a8152576/public_html/SecretSanta.html on line 41 confused about why. This is the line 41: if(isset($_POST('submit')){ this is the php of my page (without the mysql data): <?php class functions{ public static function chooseGiftee($SS){ $done = false; while($done=false){ $sqllink= mysql_connect($mysql_host,$mysql_user,$mysql_password); if(!$sqllink){ echo "Could not connect! Please Try Again"; mysql_close($sqllink); } else { $selectGiftee = "SELECT * FROM SecretSantas ORDER BY RAND() LIMIT 0,10;"; while($row=mysql_fetch_array($result)){ $results = mysql_query($selectGiftee); if(!$row['Gifter']=''){ $done=false; } else { $gifteeResults = $row['Name']; $addSS = "INSERT INTO SecretSantas (Gifter) VALUES ('" .$SS. "')"; $done=true; return $gifteeResults; } } } mysql_close($sqllink); } } } if(isset($_POST('submit')){ $echoName = functions::chooseGiftee($_POST['gifterName']); echo $echoName; } ?> This is html: <form id="form1" name="form1" method="post" action=""> <p> <label>Your Name: <input type="text" name="gifterName" id="gifterName" /> </label> <input type="submit" name="submit" id="submit" value="Submit" /> </p> <p> </p> </form> Confused about the issue, first time using functions. Thanks in advance, Brandon This is object programming right? Is there a performance issue with this? for example: $notfications = ( blah blah ) ? : ''; then if ($notificatiosn != blabla){ echo 'hey'; }or.... $notifications = function(){ do my stuff here then return 'hey'; }Which way is faster or slower? Reason I Ask this is because I've been doing some object orientated programming in javascript, and didn't know you could do it in php. I'd rather do the objective way so I don't have to use so many freaking variables above the regular way, lol. Edited by Monkuar, 22 January 2015 - 12:22 PM. I am trying to write a program that sends out a newsletter but I am lost at returning an array of emails. This is what I have
<?php require("../PHPMailer/class.phpmailer.php"); include 'includes.php'; $mail = new PHPMailer; $subject = $_POST['subject']; $text = $_POST['newsletterBody']; $unsubscribe = "<br /><br /><br /><br />If you would no longer like to receive these emails, please <a href='removeemail.php'>Click Here</a> to unsubscribe."; $mail->IsSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup server $mail->Port = '465'; $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '****EMAIL ADDRESS****'; // SMTP username $mail->Password = '****EMAIL PASSWORD*****'; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted $mail->From = '****EMAIL ADDRESS****'; $mail->FromName = '****NAME****'; $mail->AddAddress('****EMAIL ADDRESS****', '****NAME****'); $email = getEmail("", $DBH); foreach ($email as $newEmail) { $addEmail = $newEmail['email_addr']; $mail->AddAddress($addEmail); $DBH = null; } $mail->AddReplyTo('****EMAIL ADDRESS****', '****NAME****'); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->IsHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $text . "<br /><br /><br /> To unsubscribe to this email please <a href='www.raven-consult.com/newsletter_remove.php'>Click Here</a>"; $mail->AltBody = $text; if(!$mail->Send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; exit; } echo "Message has been sent <a href='newsletter.php'>Return back</a>"; ?>This is the portion of the includes file that you need to know. function getEmail($inId, $DBH) { if (!empty($inId)) { $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId"); $blogstmt->bindParam(":userId", $inId); $blogstmt->execute(); $postArray = $blogstmt->fetchAll(PDO::FETCH_ASSOC); } else { $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails"); $blogstmt->execute(); $postArray = array(); $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC); foreach($results as $row){ $myPost = new nlEmails($row['id'], $row['email_addr'], $DBH); array_push($postArray, $myPost); } } return $postArray; $DBH = null; } class nlEmails { public $id; public $email; function __construct($inId=null, $inEmail=null, $DBH) { if(!empty($inId)) { $this->id = $inId; } if(!empty($inEmail)) { $this->email = $inEmail; } } }When I try and submit the newsletter to be sent out all I get back is this error. "Cannot use object of type nlEmails as array ......" phpfreaks I am querying a database using pdo but I keep getting an array that returns two results. As you can see from the array below it returns the id and result and then repeats the result . I only want the keys with text to be returned. Any help would be great. Code: [Select] ( [0] => Array ( [Ticket_ID] => 2 [0] => 2 [Customer_id] => 1 [1] => 1 [Business_Name] => [2] => my database method is Code: [Select] private function queryFetchAllPDO($query) { try { $this->dataObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $this->dataObj->prepare($query); $sth->execute(); echo"I am here"; $result = $sth->fetchAll(); print_r($result); // $stmt = $this->dataObj->query($query); // $stmt->setFetchMode(); // $result = $stmt->fetchAll(); } catch (PDOException $e) { $e->getMessage(); } return $result; } and the query method is Code: [Select] private function clieViewHome() { //find user id $sql = "SELECT Customer_id FROM customer WHERE Username='" . $this->user . "'"; $sessAccess = $this->connection->getQueryFetchPDO($sql); foreach ($sessAccess as $value) { $userID = $value; } //place into query $sql = "SELECT * FROM tickets WHERE Customer_id ='" . $userID . "'"; $tableArr = $this->connection->getQueryFetchAllPDO($sql); print_r($tableArr); foreach ($tableArr as $key => $value) { $return .= "<tr>\n"; foreach ($tableArr[$key] as $value2) { $return .="<td>" . $value2 . "</td>\n"; } $return .= "</tr>\n"; } return $return; } Hello. I'm new to php and need a little help please. I try to build a class that return an Array of all the table in my db. and be able to get all the data by there col name (like username, password....) but all i got is the last record from the db. here is the class: <?php class db{ function getall($table, $search){ $sql = "SELECT ". $search ." FROM " . $table; $result = mysql_query($sql) or die('Error, insert query failed' . mysql_error()); while($row=mysql_fetch_assoc($result)){ $data = $row; } return $data; } and this is in the html page: $data = $db->getall("users", "*"); foreach($data as $row){ echo $row['fullname']; echo "<BR>"; } can anybody help me with that? I need to return a specific key from the object converted to array but it seems that it dosent work Code: [Select] $toarray = (array)$tmp; $name = array_keys($toarray,'name'); print_r($toarray); print:Array ( [id] => 9 [name] => dfd [text] => fdsf [rating] => 0 [totalv] => 0 ) and when i try to return the key Code: [Select] print_r($name); Array ( => rating [1] => totalv ) But I only need the key whit the 'name' value |