Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




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:




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
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 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:

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?

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.

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?

Query Giving Array As Result
I just started PHP and getting the following error when trying to read and echo something from my DB. I get Array as an result of a working SQL query (I tested it in PHPMyAdmin SQL Query) and it should be something else. Array doesnt return in the database i selected, but still it's here.

<?
$host="localhost";
$user="xxxxxxxxx";
$password="xxxxxxxxxxx";
$dbname="mohaaleague";
$connection = mysql_connect($host, $user, $password) or die ("Kan niet verbinden");
$clan = "Belgian Fun Clan";
$db = mysql_select_db ($dbname,$connection) or die("Je Stinkt");
//SELECT clan FROM clan WHERE clan='Belgian Fun Clan'
$query = "SELECT clan FROM clan" or die("Query Mislukt");
$result = mysql_query($query) or die("Query Mislukt1");
$row = mysql_fetch_array($result, MYSQL_ASSOC) or die("Query Mislukt2");
extract($row);

echo($row. "<br>");
if ( $clan == $row )
{
echo "het werkt";
}
else
{
echo "het werkt niet";
}
$disconnect = "mysql_close";
?>

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?

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

};

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:

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?

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:

Displaying Result 1-8, Then Result 9-17 Etc.
I dispaly the results from the database like this.

<? while ($row = mysql_fetch_array($prod_result)) {
$small = $row[0];
echo"<td align=center><img src="produkter/hardware/decks/$small"></strong></td>";}?>

But if there are more than 8 results, I wnat to dispaly the first 8 on one page, then the next 8 on the next page...How can this be done?

Nesting Result Loops Within Result Loops Possible?
I'm looping through a query, and inside the while result output, I am trying to loop through a second query (created from the 1st query's row results).

I have checked that both queries return info.

I can see that the 1st while result output works fine, but when I get to the inner while result output, it never returns any rows (nothing in the while loop evaluates).

So, IS it possible to nest one query's output loop within another, or am I doing something wrong?

SQL Last Result
When querying and doing a loop I want to specify that the last result of the loop does not include a horizontal line. How would I do this?

Outputing Result Once Only
Hi,

I have a php script that looks up mysql records, on the basis of keywords entered by the user.

The records are in tables making up a message board system, and the search works both for 'top-level' messages, and for replies.

The results lists the 'top-level' message (ie the entire thread), even if the search matched text in a reply.

However, I am having a problem making sure the thread is not listed more than once if the search matches several replies in the same thread.

At the moment, the search looks up all the rows containing the search text, then the message starting the thread if the search has matched a reply, and the results are output in a while loop. I have tried making a long string containing all the id's of the displayed rows, usingsomething like $displayed .= _$row[id]_ in the loop, and then ereg("_$row[id]_", "$displayed", $array) earlier in the loop to see if this message's thread id is already listed, and skipping it if it is.

However, I can't seem to get this to work. Also, this seems like a really inefficient workaround. Is there a better way to do this?

Result Using Two Variables
Probably a real simple solution but I can't for the life of me work it out.

I have:

$pollitem_1
$pollitem_2
$pollitem_3
$pollitem_4

if I do a for loop for the amount of items, is it posiible to have a variable for the number after the _ ?

e.g....

Weird Result? Php 4.4.0
I have a variable v with the value -1. After v++ it has the value "" not
0. Since I am using it for a subscript, the "" value is not overwriting
the 0 element of the array as desired. Should v++ ever give a
non-numeric value?

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:

To Display Nothing If Result Is None
Below is the script for displaying the data from a table. Is it possible that if there is no data, then the whole table should not display and not only the result field. Code:

Result Set Problem
I am new to programming in PHP however, this should be a pretty
straight forward answer. I have three queries that I am pulling for a
content form page.

1) The Author List
2) The Content Page (pulls the PK, Title and the Description of the
content.
3) The Category List

When I attempt to pull the data the only result set I get back is from
the Item #1 query above. Now, I made sure that there is data in the
tables, but I still get no data back for the other two queries(????)

Is there something that I missing when connecting to PHP/MYSQL? Do I
need to take some additional steps??

Any help would be greatly appreciated. I've been struggling with this
problem for several hours now scratching my head why this is.

:-)

// here is the PHP Code I am using

<?php
$db = mysql_connect("$DB_SERVER", "$DB_SERVER_USERNAME",
"$DB_SERVER_PASSWORD");
mysql_select_db("$DB_DATABASE",$db);
//result set 1 - get members
$result_M=mysql_query("SELECT * FROM tblMembers",$db);
$myrow_M=mysql_fetch_assoc($result_M);
//result set 2 - get content ID
$result_C=mysql_query("SELECT * FROM tblContent WHERE
contentID=1",$db);
$myrow_C=mysql_query($result_C);
//result set 3 - get categories
$result_Cat=mysql_query("SELECT * FROM tblCat",$db);
$myrow_Cat=mysql_query($result_Cat);.....

Oracle->not Same Result From Php And From Sql*plus
Here is my query, ran from oracle sql*plus:

SELECT mrbs_room.id, start_time, end_time, name, mrbs_entry.id, type
FROM mrbs_entry, mrbs_room
WHERE mrbs_entry.room_id = mrbs_room.id
AND area_id = 101
AND start_time <= 1076068800
AND end_time > 1076065200

Here is the correct result :
SQL> Connected.

ID START_TIME END_TIME NAME ID T
---------- ---------- ---------- ---- -- -
82 1076065200 1076068800 test 41 I

Ran from php, I got this :

ID START_TIME END_TIME NAME T
---------- ---------- ---------- ---- -- -
41 1076065200 1076068800 test I

the two ID fields are named with their table name, but php keep the second
value and display it as the first one.

Paging Through Result Set
Using PHP to query a MYSQL db, I am attempting to portion the result set on multiple pages. I see this technique used on this site. example: If a user query yields 30 results I want to display 5 results at a time allowing the user to page forward or back through the results.

Pulling One Result From DB
I want to echo a client name to the header of a webpage. PHP Code:

Result Handler Set?
I'm getting an error which get's reported something like "can't save result handler blabla".. .. i didn't note the exact error at the time and i can't bring it back cuz i deleted my whole database and started from scratch.. anybody know what this is about?? i'm pretty sure it's something to do with mysql.. it shows with mysql_error().

Search Result Help
I am trying to do the following with my search script that looks for records
in a mysql table. The following is an example of what I am trying to do.

Text being searched:
--
The brown fox jumped over the green fence then jumped into the web monitor.
It was hurt so it jumped backwards and fell on its!
--

The word we're searching for "web".

The results should look like

--
...then jumped into the *web* monitor. It was...
--

Are there any functions out there that will do this? Or what would it take
to make one?

How Could I Paginate The Result Set?
I would like to do something like this:

select * from myTable where ... pagesize 10 page 1

How could I do it elegantly in:

1. PHP+MySQL before MySQL 5 (without stored procedures)
2. MySQL alone (with stored procedures)

Mysql_query Result
I have a small problem with PHP and MySQL. I want to know how to check if a value is existing in a MySQL database using PHP. The code is below: PHP Code:

Result Sets
I am having alot of trouble trying to append a result set using a loop. I am taking a number from options from a select option list in a form and for each of these i want to execute the statement.

for($y=0; $y<$totaltown; $y++) {
$result=select statement}

and then out put the info using a while loop. My problem is the result set keeps overwriting itself until it produces 0 results. I have tried using $result+=$result but it is then no longer a ersult set. The code i have works fine when i only want to produce all hte results on one page but i am paging the results which is where my problem lies ie LIMIT.

Incorrect Result
i try to insert a text in a database (mysql)

in this text, there are php code i want to display... i use
<code>...</code> to do this job

str = $_POST['texttutoriel'];
$str = preg_replace_callback('`&lt;(code|url|img)&gt;(.+?)&lt;/1&gt;`si',
'bbcode', htmlentities($str));
$str = mysql_real_escape_string($str)

my bbcode function:

function bbcode($m) {
switch($m[1]) {
case 'code' :
return '<div class="code"><pre>'.$m[2].'</pre></div>'
break;
//...
}
}

Looping A Result
Im new to PHP and MySql, Im trying to setup a really basic news script for me to use for my site 2design4.com. PHP Code:

Maths Result...
I have a mathematical calculation, and for some reason if i put "1" into the input this is the result i get :

Quote1 Muscle Building sessions giving you a strength gain of 4.99999999999E-5.

I have put a script in to cut the decimals so that it'll only go as far as 5 decimals but it still keeps coming up...

$DecimalRemovalStrengthresult = number_format($GainTotalStrength,5);
$DecimalRemovalStrength = number_format($NewStrength,5);
That is what im using to strip the number down so it should only show "4.99999"

If i don't put "1" and I put say anything above 1 it'll work fine and only show a figure of 5 decimal places such as 4.99000.

So what is actually happening to the number to come up with 4.99999999999E-5 ? Does the value mean infinite number or something else?

Result Displays Seven Times In A Row
I'm trying to list out songs of a specific album and I think my code is fine. The only problem is that all the songs are displayed seven times. Everything else is fine.

Another Invalid Result Resource
Sorry to ask a debugging question, but I've been fooling with this thing all day, and I can't see what the problem is. $query is passed from search form:

$result = mysql_query("select id, date, title, text, reviewer, email, score, cover, url, url_title, hits, type, creator, release, upc, quote from one7_reviews where title LIKE '%$query%' OR description LIKE '%$query%' OR creator LIKE '%$query%' OR url_title LIKE '%$query%' ORDER BY title ASC");

$num = mysql_num_rows($result);

I keep getting "Supplied argument is not a valid MySQL result resource "

Can I Parse A SQL Result As A Php Include?
I'm trying to use a MySQL database as a repository of common classes and functions, and would like to be able to get the resultant string, addslashes, and then actually execute the string as if it was an included file. I can do this by writing a temp file, then including it, and then deleting it, but any speed benefits are lost. Is there a way to actually parse the results as if they were an external include file? Thanks for the help.

Weird CURL Result
I am having a problem using curl and when it returns the page it has all of the images listed as local files to my server, I am assuming this is because the design of the site I am accessing, but shouldn't cURL recieve the site the same way a browser does and not show files local to me. I can adjust it using string replace methods but it seems a bit troublesome to do so:

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.

Query Result = Resource ID #10
I have an array $countertop.... i run through each one like this.
PHP Code:

Free Result Doesn't Seem To Be Working
I have a section of code that is bothering me because I do not understand the error being recieved. I am running a mysql query inside of a function that is called several times here is the function. PHP Code:

Format Table With PHP Result
I have to create some kind of dynamic page, logic is next: i have integer in variable and i need to create certain number of fields based on that int. example
$variable = 6 and I need to have table with 6 fields, 4 in one row and 2 in second....my problem is how to do that, how to get new <tr> when number in bigger than 4.

Can't Output Result Set For The Second Time
I made a db query and i output the data mysql_fetch_array. it's fine for the first time but if i would like to print the loop the second time, it doesn't seems to work. PHP Code:

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?

To Free Mysqli Result Or Not
In php documentation there is this note about mysqli_free_result():
Note: You should always free your result with mysqli_free_result(),
when your result object is not needed anymore.

With the similar non-mysqli function there is this note:
mysql_free_result() only needs to be called if you are concerned about...

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?

Getting Result From Diff Tables
I've got several tables in my database which are all named table_1 , table_2, table_3, table_4, and so on. each table is built up like this:

user | points |

How would I get the sum of the points from all tables together for each user and them order them by that sum?

Strange Math Result... 1-1= -1 ???
See something weird on this result?

632.35 - 632.35 = -1.13686837722E-013

If anyone has seen something similar, please let me know!

this a part of the code:

$total_due = abs( $order_total ) - abs( $total_paid );
echo( $order_total . " - " . $total_paid . " = " . $total_due );

I've added the abs() in order to be sure that I'm dealing with
numbers, I've also used is_numeric() and confirmed it.
The echo() is showing the result I pasted up there.

Paginating Result For Two Queries
My page pagination works fine, but the code is just messy. Because I have two queries, one based on getting the ID number ($_GET['ID']) and one based on searching by keywords ($_POST['keyword']), I almost have duplicate codes for both.

For example,

if($start!= 0) {
if($browse) { //for $_GET query
echo 'Previous</a> ¦ '
}
else { //for $_POST query
echo 'Previous</a> ¦ '
}
}

I am not putting the full version of codes down as that would be too much. But hopefully, you'll get what I mean. I have to list "echo 'Previous</a>' twice because one's for the get query and the other's for the post query. So a lot of duplicate codes. How could I shorten the codes a bit?

Paginating Result Sets
First attempt at doing an exercise on paginating result sets

When I run the code, I receive the error "Fatal error: Call to
undefined function: mysql_fetch_objects() in
/homepages/17/d23395818/htdocs/en/test.php on line 48"

Line 48 is while($row = mysql_fetch_objects($result)) Any ideas?? Have
I missed an obvious mistake. (full code below)

<?php
//sets number of records and ref number in database to search by
$records_per_page = 2;
$search = "123-456-BSE";

//look for starting marker
(!$_GET['start']) ? $start = 0 : $start = $_GET['start'];

$connection = @mysql_connect('???', '???', '???');
if (!$connection) {
echo '<p>Unable to make database connection.</p>'
exit();
}

if (!@mysql_select_db('???')) {
exit('<p>Unable to locate database.</p>');
}

//create and execute query to count records
$query = "SELECT COUNT(*) FROM schott_news WHERE userID='$search'";
$result = mysql_query($query);

//get total number of records
$row = mysql_fetch_row($result);
$total_records = $row[0];

//if records exist
if (($total_records 0) && ($start < $total_records))
{
//create and execute query to get batch of records
$query = "SELECT userID, username FROM schott_news WHERE
userID='$search' LIMIT $start, $records_per_page";
$result = mysql_query($query);

//iterate over record set and print data
echo '<table border=1 cellpadding=10>'
while($row = mysql_fetch_objects($result))
{
echo '<tr>'
echo "<td>$row->userID</td>";
echo "<td>$row->username</td>";......

Passing Result To New Page.
I have a search result with a link which links to the ID# of the record. By clicking on the link I would like the rest of the record displayed. What will my script look like to pull a particular record ID?


Copyright © 2005-08 www.BigResource.com, All rights reserved