I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.
Related
can someone help me on the proper way of using a variable with multiple values in MySQL LIKE clause?
by the way, I have two tables teacher and student.
Teacher table contains. (fname,lname,subject,yr,sec) columns and for the student table (lrn,yr,sec)
what I'm trying to achieve is to count the total number of students of the teacher from all sections.
Here's my query for getting teacher's sections:
<?php
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result)) {
$section = $rowx['sec'];
}
?>
echoing $section output this: Our Lady of FatimaOur Lady of Guadalupe
Heres my query to count the students.
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE
sec LIKE '%$section%') AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
Output: the count works but only the first value [Our Lady of Fatima] of $section is getting recognized by LIKE clause, so only 1 section is getting counted.
by the way, sorry for my bad English and explanation.
Use Section as a input for second query:
<?php
$final_result = array();
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result))
{
$section = $rowx['sec'];
$ratequery = mysqli_query($con, "SELECT *, (SELECT COUNT(*) FROM student WHERE
sec =$section) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
array_push($final_result,array("section"=>$section,"rateresult"=>$rateresult));
}
var_dump($final_result); // Display section wise data
?>
somehow I have managed to achieve my goal it but in other way . I used WHERE IN clause instead of LIKE clause. stored my query results into an array.. then used implode to add seperator.
Thanks for the help mr. #ashnu
<?php
$query="$con, select *from teacher where lname = 'Uy' and subject = 'Science & Technology 7'";
$result = mysqli_query($query) or die;
$sections = array();
while($row = mysqli_fetch_assoc($result))
{
$sections[] = $row['sec'];
}
$string = implode("','",$sections)
?>
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE sec IN ('$string')) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
I am creating a simple drag and drop jquery game and it requires a shuffled resultset of 10 rows from my database table. I am able to achieve this by repeating 10 separate blocks of queries, but I am sure there must be a more elegant way to do this. I tried many things, with loops and append etc. but I can't get the loop-way working.
I can't get this loop version to work:
<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);
/*
// then loop to fetch all data from MySql table with spanish, english
// CANNOT GET THIS WORKiNG ?
for (i = 0; i < 10; i++) {
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$rand_value.append(i) = $row['english'];
$name.append(i) = strtoupper($row['spanish']);
}
*/
Writing it out works, but there must be an easier way...
<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);
// and so on to run 10 queries total
?>
Simplify everything by using RAND() in your query. Use just one query and retrieve all ten rows in a shuffled order.
$query="SELECT id,english,UPPER(spanish) FROM colors ORDER BY RAND() LIMIT 10;";
$result=mysqli_query($link,$query);
while($row=mysqli_fetch_array($result)){
// prepare and handle your results using: $row['id'], $row['english'], $row['spanish']
}
EDIT: I've added UPPER() to the query so that the spanish values don't need to be modified later in your php.
I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";
I am trying to perform a query inside a while loop that is getting values from a column. I am trying to query first to get all my values from a column in my DB and then get the count of how many times that value is in that column.
Examples of output trying to get
myValue is in the column 3 times
myOtherValue is in the column 10 times
myOtherOtherValue is in the column 22 times
Example of code
$sql = "SELECT DISTINCT id, columnName FROM tableName";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
function myCount($id)
{
$query = "SELECT COUNT(*) FROM tableName WHERE name = '$id'";
$result = mysql_query($query);
$count = mysql_fetch_array($result);
}
echo "$id is in the column $count[0] times";
}
You can't define a function inside the while loop.
Using COUNT(*) with a GROUP BY name clause, then you could solve the problem with only one query.
I'm working in PHP and MySQL to create and list a membership directory. I have three tables - company, contact and branch. Companies have Contact people, and some but not all companies have Branches, which also have Contact people. I am using LEFT JOIN in my first query to connect the contact people to their respective company, and loading the results into an array, which works using the following code:
// Retrieve all the data from the "company" table
$query = "SELECT * FROM company LEFT JOIN contact ON company.company_id = contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, contact.cont_rank";
$result = mysql_query($query)
or die(mysql_error());
// Build the $company_array
$company_array = array();
while($row = mysql_fetch_assoc($result)) {
$company_array[] = $row;
}
Now I am trying to figure out how to run a second query, which needs to select from my branch table all branches whose company_id match the company_id stored in my above array: $company_array. I then want to store the results of the second query into a second array called $branch_array. I have tried this:
// Retrieve all the matching data from the "branch" table
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
}
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
But this does not seem to work... Can anyone give me an example of how to do this? The query needs to run so that it checks each different company_id in my $company_array for a match in the branch table - hopefully the question makes sense. Thanks.
i think your while should be inside your foreach statement so that your $branch_array can be filled with results of all company_id values, not only the last one :
foreach($company_array as $row) {
$query2 = "SELECT * FROM branch LEFT JOIN contact ON branch.branch_id = contact.branch_id WHERE branch.company_id = '".$row['company_id']."' ORDER BY branch.br_name, contact.cont_rank";
$result2 = mysql_query($query2)
or die(mysql_error());
// Build the $branch_array
$branch_array = array();
while($row2 = mysql_fetch_assoc($result2)) {
$branch_array[] = $row2;
}
}