MySQL Result To Real Array In Function
I'd like to create a function which input is the result of a mySQL query. The output should be exactly the same, only not a mySQL result array, but a 'real' array. So it should also get the fieldnames returned by mySQL and use those as keys.
I can't get things to work properly: it should return a multidimensional array, like
$result_array[1] = array( [field1] => field1 value, [field2] => field2 value, etc. )
somehow my result is (with code below)
$result_array[1] = array( [0] => field1 value, [field1] => field1 value, [1] => field2 value, [field2] => field2 value, etc. )
+++++ code ++++++
$get_res= mysql_query(QUERY);
if( $res = mysql_fetch_array( $get_res ) ) {
do{
$result[] = $res;
}while( $res = mysql_fetch_array( $get_res ) );
};
foreach( $result as $key => $value ){
print_r($value);
};
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Mysql Result Into Array?
I have a shopping cart script sending info to a processor. I need to send the qty's and item name's in some sort of string via a single variable to the process form. i.e. (3) Hipster Turnips, (6) Butter Milk Baby Brains, (2) Super Freaks Code:
Replacing Array With Mysql Result
I wanted to repalce the following line of code $data = array(40,21,17,14,23); with
for($i=0;$i<$numrows;$i++) { //print(mysql_result($result,$i,2));print("<br>"); array_push($data,mysql_result($result,$i,2));}
where mysql_result($result,$i,2) is the value and when i print it displays the values. But $data array is the Y axis value for drawing a chart. Here I wanted to replace the hard coded value with values from mysql but the second code does not function. Does anybody have idea how can I replace the $data array or what may be the problem with my coding The first one works but the second one does not work but in both cases it does not display any error.
Assign MySQL Function Result To PHP Variable
I know to use: mysql_fetch_row($result) to convert a row from a SQL query result set into an array for use with PHP. but in the case of SQL queries that return one value, such as calls to MySQL functions, is there another PHP mysql api function I should use.
For example, right now I use a "workaround" technique from PHPBuilder: $result=mysql_query("SELECT COUNT(*) FROM tablename"); list($numrows)=mysql_fetch_row($result);
Rather than using this "workaround" code is there a way to simply assign the result of the MySQL function query to a variable.
$result=mysql_query("SELECT COUNT(*) FROM tablename"); $numrows=mysteryfunction($result);
If Result Of Mysql Query Is Only One Row/column, Why Use An Array?
If I'm doing a very specific select statement, which I know will only ever return one value, can I get that resulting bit of data without storing it in an array or object? If not, is mysql_fetch_array() the fastest method for getting this one value?
Can I Put A Mysql Query Result Directly Into A Multidimensional Array?
I have two joined tables:
Departments - which contains the department description and a key Positions - which contains position data
What I'm attempting to achieve is to display the department title in one table cell and then list all the positions associated with that department in the cell under neither the title. I need to generate a table two column table with as many rows as required, depending on the number of departments, which is dynamic.
Do this I'm trying to turn the result of my SQL query into multidimensional array e.g. dept = VioP positions = "designer", "engineer" etc, which I can do then use to generate the table.
I've done a search on the forum and looked around the manual and I'm stumped on how to achieve this, a point in the right direction would be greatly appreciated. The query I'm using is below. PHP Code:
Making Mysql Result Into Multi-dimensional Array
My php problem is I want to make the result of 3 tables linked through foreign keys into a 3-dimensional array that reflects their relationship without repetition and without having to call the database more three times.
I know I'm doing a couple of things wrong, one thing for instance is initializing a variable at the end of the loop to remember the previous value s that it does not repeat itself, surely there must be a more elegant way to go about this, but I'm lost and I've been stuck on this all day. Code:
A Real Challenge For Real PHP Programmers
<?php /* A challenge to every PHP programmer.The one who's gonna solve this problem would be deemed as
PSP(PHP Supreme Programmer).The problem is this : You have to write a script that displays a list of
categories and subcategorieslike this one:
<select name="category"> <option value="1">Main</option> <option value="2">Main > Computers</option> <option value="4">Main > Computers > Hardware </option> <option value="8">Main > Computers > Hardware > PC</option> <option value="7">Main > Computers > Hardware > Mac</option> <option value="9">Main > Computers > Hardware > Atari</option> <option value="11">Main > Computers > Hardware > PC > History of Pc</option> <option value="">etc...</option> </select>
The categories and subcategories details are stored in these two tables in a MySQL database. -categories : the categories names and ids. -cat_relations : the relations between categories.It shows which subcategory belongs to which category. The belongings between categories can go very deep and the number of categories is unlimited. This script will create the two tables and fill them with sample data. All you need to do is to change the four variables below. You can send the script back to this email : yasbergy@yahoo.com. */
//Here starts the script. Please change the values of these variables to fit your settings $user = "prospective_PSP"; $database = "db"; $server = "localhost" ; $pwd = "" ; //Connection to the database that you created mysql_connect($server,$user,$pwd) ; mysql_select_db($database); //Creation of the two tables : categories and cat_relations $categories = " CREATE TABLE `categories` (`id` INT not null AUTO_INCREMENT, `name` VARCHAR(100) not null , PRIMARY KEY (`id`), INDEX (`id`), UNIQUE (`id`)) comment = 'The categories details' "; mysql_query($categories) ; $cat_relations = "CREATE TABLE `cat_relations` (`id` INT not null AUTO_INCREMENT, `daughter_id` INT not null, `mother_id` INT not null , PRIMARY KEY (`id`), INDEX (`id`), UNIQUE (`id`)) comment = 'Which category is the daughter of which category'"; mysql_query($cat_relations) ;
//Filling the two tables with sample data $cats = array('Main','Computers','Countries','Hardware','S oftware','Programming languages','Mac','PC','Atari','Winamp','History of the PC','IBM','Components','High level','USA','NYC','LA','Manhattan','India','Winzi p'); for ($i=0;$i<count($cats);$i++){ $sql = mysql_query("insert into categories (name) values('".$cats[$i]."')"); } mysql_query("insert into cat_relations (daughter_id,mother_id) values (2,1),(3,1),(4,2),(5,2),(6,2),(7,4),(8,4),(9,4),(1 1,8),(12,8),(13,8),(10,5),(20,5),(14,6),(15,3),(16
,15),(17,15),(18,16),(19,3)"); //Now you can have a look on them through phpMyAdmin ?>
Trying To Return Mysql Array Items From Function
I am writing a calendar script which returns events, holidays etc.. from MySQL for days with events. This was easy BUT then I tried to return multiple events on some days and thats where I am stuck.
I found some examples of returning arrays from functions from functions but they all use some form of array(Ƈ',ƈ',Ɖ') and then use a for loop... I am using mysql_fetch_array so this does not seem to work... First, here is some of the code from the function where I am returning the value: PHP Code:
Read Data From MS Access Into MySQL In Real-time
I am currently working on a project that involves reading information from a inventory system into Access via ODBC and display the info on the web site using MySQL.
I would like to create a live link between the MS Access(local) and MySQL (remote) whenever the inventory system is updated MySQL will be updated as well.
I know that MyODBC will let me do the opposite of what I would like to accomplish by reading data in MySQL into Access. Is it possible to do the reverse way.
Add Sql Result To An Array
I am trying to add the results of a query (specifically a particular field's value) to a new array. The result is either an empty array or the last row in the query result instead of all the rows. Code:
Query Result Navigator Function
I've just updated this, and I thought I'd also say that not only can this provide a page navigation for MySQL or other database results, but can be used to navigate other lists.. such as a file list. PHP Code:
Adding Result Row To Mail Function
I have an email script that will pull the addreses from my club membership database. That part works fine. the problem I am having is being able to include row results inside of the actual email message. My message variable is something like this: Code:
Simple Array From DB Result
I have a simple DB query which puts a set of values into a pull-down menu as follows:-
Mysql_fetch_row($result) In Array
I'm generating 20 rows of textboxes in PHP. Some textboxes are pre-filled with information from mysql table. Code:
Load Result Contents Into An Array?
Is there a way of loading an entire result set into an array without manually looping though mysql_fetch_row?
Moving A Query Result Into An Array
I have read all the array stuff done searches for examples, but am still not clear if there is a way to do a query from a MySQL table and move those vaules into an arry.
I am sure it can be done, but I thought I would find a function that would do it. Am I just overlooking something?
$resultID = mysql_query("SELECT DISTINCT slot FROM items"); while(list ($slot) = mysql_fetch_row($resultID)){echo"$slot";}
So anyone have a good way to move the result into some array?
Function To Test If Mysql_fetch_array($result) Pointing Last Record?
I try to perform multiple insert statment, but the problem is in the below codes, the last sql concatenation ends with ",". I wonder if there is any php function to test if the $result set contains the last record.
------------------ //Get topic id of vote_topic from last insert record $sql_topic_id = "SELECT topic_id FROM vote_topic ORDER BY topic_id DESC LIMIT 1"; $result = mysql_query($sql_topic_id,$conn); $row = mysql_fetch_array($result);
//Get all student info from stuinfo $sql_strn = "SELECT strn from stuinfo"; $result1 = mysql_query($sql_strn,$conn);
//Dump all student strn into vote_status. //Multiple insert statement? How? $sql2 = "INSERT INTO vote_status (strn,topic_id) VALUES "; while ($row1 = mysql_fetch_array($result1)){ $sql2 .= "VALUES ('".$row1[strn]."','".$row[topic_id]."'),";} mysql_query($sql2,$conn); ---------------------
An Extra Last Empty Field In An 'mysql_fetch_array' Result Array?
I seem to get an extra empty field in every 'mysql_fetch_array' command I issue. For example:
I have a simple table 'tblName':
ID Name 1 Jane 2 Joe 2 Doe
The following code:
$oCursor = mysql_query("SELECT ID from tblName WHERE Name='Jane'"); if (!$oCursor) { $bGo = false; } else { $aRow = mysql_fetch_array($oCursor); }
results in:
count($aRow) = 2;
$aRow[0] = 1; $aRow[1] = ''
Am I missing something, doing something wrong, a wrong PHP setting?
Mysql Fetch_field Gets Table Alias, Not Real Table Name
After a SQL 'select .... from tablename alias' the mysql_fetch_field function returns a value $result=>table which will contain the alias, not the actual table name. Is there a way to get the actual table name ?
I am running mysql 4.1 and php 4.4
Getting Result From Mysql
I am using this code to get some data from a mySQL database. Which seems pefectly valid to me. Here it is: Code:
MySQL Result Resource
I want to build a function that, depending on the input, will either return the results from a MySQL query or do something else and return one of several messages.
My problem is checking the return value to see which is returned. Is there a php function that checks a variable to see if it is a valid MySQL result resource? I looked through the manual and couldn't find anything.
MySql Result In Textarea
I have a script to display mysql query results in a table. I'd like to display the results in a scrollable textarea. Is there a way to do this?
Returning 1 Result From MySQL
I know the usual way of receiving results from MySQL, useing a while loop e.g.
$sql = "SELECT * FROM users WHERE email='joe@hotmail.com'"; $result = mysql_query($sql,$connection); while ($row = mysql_fetch_array($result)){ echo $row["firstname"]; echo $row["lastname"]; echo $row["email"];}
BUT, if I know they only 1 result is going to be returned, is there a way to do this without using a while loop? So if I only wanted to get only the firstname of the person with email joe@hotmail.com. can I do this without a while loop or do I have to use one?
Total Result Php Mysql
PHP Mysql limit the result to 5 I can display the 5 results using a do & while which it ok.
I want to list the total or all the results without using a do or while
this is so I can combine the results and remove duplicate words from the total results
I.E. Do & While row result 1 this is the top 2 this is the bottom 3 this is the middle 4 this is the end 5 this is the finish
This is what I want to do: result this is the top this is the bottom this is the middle this is the end this is the finish
modified result:: this is the top bottom middle end finish
Invalid MySQL Result
I keep getting the following two errors:
Warning: Supplied argument is not a valid MySQL result resource in /home/xxx/public_html/articlepro/newarticle.php on line 75
Warning: Supplied argument is not a valid MySQL result resource in /home/xxx/public_html/articlepro/newarticle.php on line 84
Here's the code which I think is causing the problem. PHP Code:
Size Of Mysql Result Set
How do I find the size of a mysql result set using php.
MySQL (DB) Result Sorting
I'm doing is taking results (fetching rows) from my mySQL database. But what I want to do is sort the results according to last name. So basically the table structure looks something like this:
id (primary key) fullname
A example rows could be: 1 John Smith
2 Mary Jane
Now what I want to do is sort the results in PHP based on last name. I'm using the Pear DB for connecting to my mySQL database. Based on the example rows I gave, Mary Jane would go first, and then John Smith. How would I go about doing this? I was beginning to split the result based on spaces, and the last word to explode, but how would I truly do this?
Modifying MySQL Result - But Not The DB
How can I modify a MySQL data set returned by mysql_query? I am basically doing a while loop over the rows, changing one field, and then doing a mysql_data_seek back to the beginning of the set before returning it. However, later calls to mysql_fetch_assoc still return the orginal data, meaning that (I assume) I am changing a copy of the data rather than the result set itself. Taking the reference (i.e. $record =& mysql_fetch_assoc($result);) did not help.
I have read a large quantity of the posts in the php.net site, googled, and read my PHP books - but have come up short on this one.
Yes, I know it's better to simply modify the DB. However, I'm working with an existing code base which is very complicated, and want to cherry pick one very well tested feature by making a change in the result set only under special circumstances.
Substr() With A MySQL Result?
I am trying to limit the amount of text exhoed from a MySQL database column. From reading around it appears the substr() should be able to do this Code:
Result From Mysql Into Foreach?
when using mysql_fetch_array($result)
I usually toss that into a while loop like so
while($row = mysql_fetch_array($result)){ ... } however I was wondering if there was a way to put it in a foreach statement like so
foreach(mysql_fetch_array($result) as $row){ ... } Is that legit? Will this work?
Not A Valid MySQL Result Resource
PHP Code:
Using MYSQL Result To Send Mail
I have wrote a program to load a number of email address from the MYSQL database. And I have use "$mail = mysql_query("select email from user;",$link_ID);
Now, I want to use mail() to send email to those e-mail account I got. What should I do for this?
Date Formatting From Mysql Result
always in the past I have done my date formatting from the query like so:
DATE_FORMAT(dateField, '%W, %b %e, %Y') AS realDate
I have tried formatting the straight date result with PHP like so:
having fetched results with mysql_fetch_array,
$newDate=$result["dateField"]; $formattedDate=date($newDate, 'm/d/y');
This doesn't work and simply returns the unformatted date as it is stored in the database.
Invalid MySql Result Resource
I have written a php script to search a MYSQL database and with the line:
$result = mysql_query ("SELECT * FROM table1 WHERE first_name LIKE '$first_name%' AND last_name LIKE '$last_name%' " ); The next line, if ($row = mysql_fetch_array($result)) { , gives me the error message
"supplied argument is not a valid MySql result resource"
Performance Of Fetching MySQL Result
Is there a real performance difference between mysql_fetch_array(), mysql_fetch_object(), and mysql_fetch_row()?
Display Of Mysql Table Result...
I have a mysql table of articles with fields:
- recordID - department - articleTitle - articleText
Using PHP, I'm attempting to get the results of the table to display as follows:
Department 1 - articleTitle 1 - articleTitle 2 - etc....
Department 2 - articleTitle 1 - articleTitle 2 - etc..
I figure I should use a while loop but can't figure out how to exit/reset the loop when a new 'department' is encountered in the $result.
Same Mysql Query Doesn't Always Return A Result
We have no access to a mysql NG on my provider's server, so we ask here:
We have a long query (long in text) with a UNION between 2 select.
We have been informed that some times the query doesn't return any result. We have tried on our server and we always get a result. BUT, trying on the hosting server, many times the query doesn't return any result and doesn't get any error.
Any idea ? does Union have any problem ? how to check if the query failed ? My hoster said that sometimes the table can be locked (if the server is overloaded) and then mysql doesn't return any result, but this seems to me an aberration.
the query takes about 0.0050 sec to execute when it doesn't return any result, and 0.030 when I get results
Mysql Search Close Result
I've to find in a table the "closer" result given some text.
Here is a little example:
given the text "Batman socks" I've to find the best matching result in choices like: -"mickey socks" -"robin socks" -"batman black socks" ->this should be found -"batman wallet" -"batman"
or given the text "leather shoes" I've to find the best matching result in choices like: -"socks" -"shoes" ->this should be found -"pants" -"shirts" -"leather wallet"
Mysql Problem Understanding Result And Id?
I can't understand why the output from this is not ƍ'?
$query = "SELECT * FROM contacts"; $result = mysql_query($query); echo mysql_result ($result, 7, "id");
I also tried adding "ORDER by id" but I still can't get it to echo 7.
MySQL Result Printing In For-loop
I have a script that count and print every week in a selected year. Now i want to connect this to the returned result from a MySQL query. Code to explain what I am trying to accomplish: Code:
How Do I Return Result Of Mysql Row Deletion
The data entered by a user on form 1 on page1.php is posted to delete.php to remove that row from a table. After the SQL operation the user is returned to page1.php.
How can I determine the success or failure of the SQL operation so I can display an appropriate response message to the user?
Different Result For MySQL And PHP String Comparison
I have issued an SQL statement "SELECT email FROM mailing_list ORDER BY email ASC"; By right the order of the email should be sorted from smallest to largest. However I got different results when I used record that was ranked higher to compare against record that was ranked lower. I got opposite results. Code:
Mail A Set Of Addresses From A MYSQL Result
I'm populating a field in MYSQL that collects email addresses for a certain topic and saves them like this:
mail1@mail.com|emailaddress2@mail.com|email3@email.com
- Basically what I'd like to do is explode the data, and set up a mailer from PHP that informs each of the addresses individually that there has been an update to the topic.
I *don't* want each of the mail addresses to be visible to all the recipients on the list, so simply inserting the data into the TO: field won't do, because then all the addresses are visible, causing security concerns. Code:
Allow The User To Sort A Mysql Result
So what i got going on is a database that has, things about a video game, including the image location. what i want to do is have a nav bar up top, so the user can select a differnt way of sorting the mysql result, from like ASC to DESC, or sort by genre.
Passing Array Of Multidimensional Array To Function
How do I pass a part of a multidimensional array to a function. I have the following (in pseudo):
$arrays[m][n]; // filled with values $chosen = 3;
function doSomething($array) { // do something with 1D array }
This fails:
doSomething($arrays[$chosen]);
Can someone explain to me why? And how to do this right?
MySQL Result Can't Be Returned From Class Method.. ?
I've been messing around with objects and classes lately and can't figure out why this wont work.
I have index.php which uses the pbMySQL class (pbMySQL.class.php) and methods: Code: include("lib/pbMySQL.class.php");
$db = new pbMySQL; $db->pbMySQL_open("localhost","user","pass"); $db->pbMySQL_useDB("database");
// $q=$db->pbMySQL_query("SELECT * FROM pbn_news ORDER BY id DESC"); $q=mysql_query("SELECT * FROM pbn_news ORDER BY id DESC");
if(isset($q)) { while($row=mysql_fetch_array($q)) { print $row['name']."<br> "; } } else { print "query returned FALSE"; }
$db->pbMySQL_close();
My problem is that when I use the first query method (which is commented; uses the pbMySQL_query() method) I do not get the mysql result returned, but if I use the same query without the method, I get the result. Here is the method from my class: Code: function pbMySQL_query($query) { if(!isset($this->conn) || !isset($query)) { print "Error : argument(s) missing.<br> "; } else { $this->query = mysql_query($query,$this->conn) or die("Error : query failed.<br> mysql said: <i>".mysql_error()."</i><br> "); if(isset($this->query)) { return $this->query; } else { return FALSE; } } }
The method returns FALSE and I don't understand why. Is it something in particular I have to do different when using a class?
How Can I Populate A Listbox With The Result Of Mysql Query?
I would like to populate a listbox with the result of a mySQL Query.
Error Message - 0 Is Not A MySQL Result Index
Could anyone explain what this might mean?
Warning: 0 is not a MySQL result index
I have a simple form set up where a user types in a keyword and then a page is displayed based on the keyword. See below:
HTML page: <html> <head> <title></title> </head> <body> <form action="submitform.php3" method="GET"> <p><strong><font face="verdana, arial, ms sans serif" size="1">id#</font>:</strong> <input type="text" name="keyword" size="15" maxlength="25"> <input type="submit" value="Go!"> </p> </form> </body> </html>
submitform.php3 page: <?php mysql_connect ("localhost", "username", "password"); mysql_select_db (dbname); $result=mysql_query("SELECT $url FROM table WHERE keyword LIKE '%$keyword%'"); list($url)=mysql_fetch_row($result); ?>
The concept is really simple. A user types in an keyword and that page is displayed. There is a database set up with a table that has two columns. One is "keyword" and the other is "url" For example row 1 the keyword is abc, and the url is http://www.abc.com.
How To Get Mysql Query Result Into Temp. Txt File
I did a lite search in the archive but didn't find anything specific to my problem. Here is what I am trying to do:
I've got a table with about 25k entries of company addresses. I need to be able to pull specific data out of the table and put it in a temporary text file and then display the result in the browser for the user to save locally.
The query part and the format of the data is all simple enough but I am having trouble figuring out how to get the data from the query into a temporary text file and then displaying that file. here is what I whipped up but it obviously doesn't work: Code: <? $tmpfname = tempnam("/path/to/file/", "FOO"); $list = mysql_query("select * from FH_LIST where State='AK'"); while ($list_results = mysql_fetch_array($list)) { $data = blah blah blah; fwrite($tmpfname, ".$data "); }
fopen($tmpfname, "r"); fpassthru($tmpfname); ?>
I get an error message saying: Warning: Supplied argument is not a valid File-Handle resource (referring to $data).
|