When I try to mysql_fetch_row the array that is created contains 2 fields from my selection at each index. I would like to ask why is this happening?
<?php
$categoryid = $_GET['id'];
include('connect.php');
$query = "SELECT
Categories_SubCategories.IdCategory,Categories_SubCategories.idSub_Category,
Categories.Name, Sub_Categories.Name from Categories_SubCategories JOIN
Categories on Categories.idCategory = Categories_SubCategories.idCategory
JOIN Sub_Categories on Categories_SubCategories.idSub_Category =
Sub_Categories.idSub_Category
WHERE Categories_SubCategories.IdCategory = $categoryid";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++){
$display = mysql_fetch_row($result);
echo "$display[3]";
}
?>
most PHP programmers use while() loop when they want to work with mysql_fetch_array().
Take a look at this sample code:
$query = mysql_query("SELECT id,name FROM tbl_members");
if (mysql_num_rows($query)) {
while ($result = mysql_fetch_array($query)) {
echo('User #'.$result['id'].' is: '.$result['name'].'<br />');
}
}
// Output can be something like this:
// User #1 is: John
// User #2 is: Sarah
replace mysql_num_rows with mysql_fetch_array or mysql_fetch_assoc
Related
I'm having trouble with pulling database information from 'rownum' column and putting it into an array and then using that array information for my next query that randomly selects one line of the array and then displays it.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
I'm not sure what I have done wrong? Does the array have to be echoed and then my $query line calls that instead?
Updated code - Solved my problem
Thanks for tips guys, it helped me wrap my head around it and came up with a working solution.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
//pick a random point in the array
$random = mt_rand(0,count($all_rownums)-1);
//store the random question
$question = $all_rownums[$random];
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
This part is what helped me solve it:
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
Happy Dance
Right now I am selecting some data from Mysql which I want to echo out, but I don't know how..
Code
<?php
// Database connection
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/opendb.php");
// News 1
$searchroutenews1 = "SELECT newsid FROM NewsHomepage WHERE id = '1'";
$handlenews1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews1);
$news1 = mysqli_fetch_row($handlenews1);
$searchroutenewsimg1 = "SELECT newsimg FROM NewsHomepage WHERE id = '1'";
$handlenewsimg1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg1);
$NewsImg1 = mysqli_fetch_row($handlenewsimg1);
// News 2
$searchroutenews2 = "SELECT newsid FROM NewsHomepage WHERE id = '2'";
$handlenews2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews2);
$news2 = mysqli_fetch_row($handlenews2);
$searchroutenewsimg2 = "SELECT newsimg FROM NewsHomepage WHERE id = '2'";
$handlenewsimg2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg2);
$NewsImg2 = mysqli_fetch_row($handlenewsimg2);
// News 3
$searchroutenews3 = "SELECT newsid FROM NewsHomepage WHERE id = '3'";
$handlenews3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews3);
$news3 = mysqli_fetch_row($handlenews3);
$searchroutenewsimg3 = "SELECT newsimg FROM NewsHomepage WHERE id = '3'";
$handlenewsimg3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg3);
$NewsImg3 = mysqli_fetch_row($handlenewsimg3);
?>
After this I require_once this in an other file, and then I echo the variables $news1, $news2, $news3, $NewsImg1, $NewsImg2 and $NewsImg3. But if I echo this variables out now it says: array.
You can fetch all this information via a single query, instead of the 6 you currently are running. Then it's a matter of putting mysqli_fetch_*() as the argument of a while, as you'll then fetch all the rows, until that function returns null - at which point you've fetched all the rows returned by the query.
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT newsid, newsimg FROM NewsHomepage WHERE id IN (1, 2, 3)");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['newsid']." ".$row['newsimg'];
}
Change however you need it to be displayed inside the while loop, and use the two variables as they are inside.
Alternatively, you can use WHERE id BETWEEN 1 AND 3 instead, but using IN (1, 2, 3) can more easily be changed to the exact ids you need.
http://php.net/mysqli-result.fetch-assoc
First you should read http://php.net/manual/en/mysqli-result.fetch-row.php
you can find there mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array mysqli_fetch_row always return array so now you can't echo array thats why it gives you array.
You can try foreach loop or for loop or while loop to display your data. there are also various methods to get array value.
Below is an example you can use.
while ($news1 = mysqli_fetch_row($handlenews1)) {
echo $news1[0];
}
I have three MySQL tables that I need to query for all of the rows. Upon getting all of the rows from each table, I need to create a multidimensional array whereby each index of that array contains only value from each of the tables. What I have right now works. But, something is telling me that there has got to be a better way of accomplishing this.
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $table) {
$sql = "SELECT * FROM ".$table."";
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$num = mysqli_num_rows($query);
$i = 0;
while($row = mysql_fetch_array($query)) {
$id[$i] = $row['user_id'];
$i++;
}
for($i=0;$i<$num;$i++) {
if(!is_array($final[$i])) {
$final[$i] = array($id[$i]);
} else {
array_push($final[$i], $id[$i]);
}
}
}
The end results is something that looks like this
$final = array(array('table_one_row_one_val', 'table_two_row_one_val', 'table_three_row_one_val'),
array('table_one_row_two_val', 'table_two_row_two_val', 'table_three_row_two_val'),
array('table_one_row_three_val', 'table_two_row_three_val', 'table_three_row_three_val')
);
I get the gut felling that this could be done much more effectively, but I'm not sure how.
Thanks,
Lance
You can make your code simpler if you make your query more explicit in selecting the columns you want in the order you want them. So for example:
$sql = 'SELECT table_one.user_id as u1, table_two.user_id as u2, table_three.user_id as u3 FROM ' . implode(',', $tables);
Then each row of your result set will have the columns in the proper order making the construction of your arrays less involved. For example:
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
while($row = mysql_fetch_array($query)) {
$final[] = array($row['u1'], $row['u2'], $row['u3']);
}
There may be issues with the order and relationships of the data in these arrays (especially if all 3 tables don't have the same number of rows), but working just off the information above, this is another way you could approach it. Something to think about anyway.
Try this:
$sql = "SELECT 'user_id' FROM ".$table;
What about:
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $tableIndex => $table) {
$sql = "SELECT user_id FROM ".$table;
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$i = 0;
while($row = mysql_fetch_array($query)) {
$final[$tableIndex][$i] = $row['user_id'];
$i++;
}
}
It is always better selecting only the columns you will use. SELECT * is not a good SQL practice.
I am using PHP/MySql to display some results from a database.
CODE
$query = "select * from users where (fname like '%".$searchTerm."%') OR (lname like '%".$searchTerm."%')";
$result = $db->query($query);
echo "yoooo";
$num_rows = $result->num_rows;
echo "<br/>".$num_rows." results st 2";
for ($i=0; $i<$num_rows ; $i++) {
$row = $result->fetch_assoc();
$fn = $row['fname'];
$ln=$row['lname'];
echo "<br/>".stripslahes($fn)." ".stripslashes($ln);
}
This shows:
yoooo
1 results st 2
But nothing more... Why? I am sure that the names I use in the associative array are the column names in the table...
I'd try to:
turn on error_reporting(E_ALL)
echo the query + make sure $searchTerm is safe(avoid sql injections)
var_dump($row)
I need all values from a table column put into an assoc array. I am having trouble finding the answer.
the table is only six rows deep.
example:
|--id--|--name--|--A--|--B--|--C--|
|--01--|--xl33--| 1.30| 2.45| 4.40|
i would like to get an assoc array for column B
name[xl33]=2.45
name[xl34]=....and so on
The trick is that the form will tell the script which column to fetch. A,B,C,D,E,F OR G
I know i could re-format the table and accomplish what i want but I need it structured the way i have it.( i have left out some columns for simplicity)
function return_column($letter){
$result = mysql_query("SELECT name, $letter FROM example") or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) {
$return[$row['name']] = $row[$letter];
}
return $return;
}
$results = return_column('A');
print_r($results);
Something like :
$col = 'B';
$name = array();
$result = mysql_query("SELECT * FROM table") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name[$row['name']] = $row[$col];
}
This creates an array $name and uses the name column as the key and the $col column for the value ...
You are looking for the mysql_fetch_assoc() function.
Example/
$query = $this->query($YOUR_QUERY);
$returnMap = array();
while ($row = mysql_fetch_assoc($query)) { array_push($returnMap, $row); }
Use mysql_fetch_assoc — Fetch a result row as an associative array.
while ($row = mysql_fetch_assoc($result)) {
$data[$row["column1"]]= $row["column2"];
..............
.........
}