Using variable with multiple values in MySQL LIKE clause - php

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

Related

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

Display Unique Values from MySQL database

I'm reporting my question to be a little more succinct. (deleted other)
I have a time reporting system I have built, and I am trying to create an adherence type report.
Esentially I'm trying to do the following:
Gather all unique names ($fn, $ln) in my database, based on a where clause and the fields practice=ccv & year=2016 (for example)
Then I also want to gather up another list of names ($fn, $ln), based on practice=ccv & year=2016 and additional where clause week=8
This will give me 2 DISTINCT lists that I can compare, and the difference will be the Outstanding timecards for week 8.
From there, I need to display all the names for submitted (from #3 above) and also the list of outstanding (by comparing the #1 and #2 above)
Thus far, I can get the list of names. However, I then need to display them with additional data from the database for each person (Region, Timestamp, etc ..)
Desired Output would be something like this:
Submitted
EMEA
John J
Wally R
North America
Davis D
Bob C
John Y
Outstanding
EMEA
Kyle D
North America
Cory T
Hugh R
John J
LATAM
etc ....
Thus far, here is what I have .. I'm sure I'm going about this the wrong way.
<?php
$con = mysqli_connect("localhost","xxx","xxx!","xxx");
//Get distinct names from practice
if ($con) {
$SQL = "SELECT DISTINCT fn,ln FROM $table WHERE year='$year' AND practice='$practice' AND archived!='yes' ORDER BY region,fn,ln";
}
$result = mysqli_query($con,$SQL);
if (!$result) die('Couldn\'t fetch records');
while ( $db_field = mysqli_fetch_assoc($result) ) {
$name[] = trim($db_field['fn']. " " .$db_field['ln']);
}
//Get distinct names for current week practice
if ($con) {
$SQL2 = "SELECT DISTINCT fn,ln FROM $table WHERE year='$year' AND week_num='$week' AND practice='$practice' AND archived!='yes' ORDER BY region,fn,ln";
}
$result2 = mysqli_query($con,$SQL2);
if (!$result2) die('Couldn\'t fetch records Again');
while ( $db_field = mysqli_fetch_assoc($result2) ) {
$name2[] = trim($db_field['fn']. " " .$db_field['ln']);
}
//$SQL3 = "SELECT fn,ln,week_start_date,region FROM $table WHERE fn IN ( '".implode("', '", $differences)."' )");
mysqli_close($con);
?>
<TABLE><TR><TD>
<B>All Names</B><BR>
<?php
foreach ( $name as $item ) {
echo $item . "<br/>";
}
?>
</TD>
<TD>
<B>Names for Week 8</B><BR>
<?php
foreach ( $name2 as $item2 ) {
echo $item2 . "<br/>";
}
?>
</TD>
<TD>
<B>Outstanding</B><BR>
<?php
$results = array_diff($name, $name2);
foreach($results as $val) {
echo $val ." - ".$val2."<BR>";
}
?>
</TD>
</TR>
</TABLE>
I think you should solve this at MySQL level.
// All names with all data
$SQL = "SELECT DISTINCT *, CONCAT(fn,' ',ln) AS `name` FROM $table WHERE year='$year' AND practice='$practice' AND archived!='yes' ORDER BY region,fn,ln";
// Names for specific week with all data
$SQL = "SELECT DISTINCT *, CONCAT(fn,' ',ln) AS `name` FROM $table WHERE year='$year' AND week_num='$week' AND practice='$practice' AND archived!='yes' ORDER BY region,fn,ln";
// Outstanding rows with all data
$SQL = "SELECT * FROM (SELECT DISTINCT *, CONCAT(fn,' ',ln) AS `name` FROM $table WHERE year='$year' AND practice='$practice' AND archived!='yes') AS `subquery` WHERE `name` NOT IN (SELECT DISTINCT CONCAT(fn,' ',ln) AS `name` FROM $table WHERE year='$year' AND week_num='$week' AND practice='$practice' AND archived!='yes') ORDER BY region,fn,ln";
This way you won't need to sort and process data at PHP-level. Can't test this since I don't have the database environment but it should work, may require some small changes.

Accessing two different tables for one loop

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.

mysql statement using a for loop php

I have a mysql query which is being to find the stock items in a certain location belonging to a certain group. Hence this is going through 4 levels of while loops. No i have given the user the ability to select the locations they want to view the stocks from. This is being achieved using checkboxes which are sent using ajax in an array. The array exploded in PHP using $offices = explode(",", $locations);. However now i want to use the locations selected in my mysql query.
$location are in the form of location1, location2, location3, location4
//selecting all locations using the statement below, however i want to select the locations that where selected by user.
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where 'wanted locations');
while($row3 = mysql_fetch_array($sql4)) {
$curr_location = $row3[0];
$sql3 = mysql_query("select Quantity from Stock_Management where Book_ID = '$curr_book' and Location_ID = '$curr_location'");
while($row3 = mysql_fetch_array($sql3)) {
echo "<td>".$row3[0]."</td>";
}
}
echo "</tr>";
I want to select the locations based on the selected locations by user, now this can be achievable using a for loop by i don't know how to include that in my sql query!
$locations = mysql_real_escape_string($locations);
$locations = str_replace(",","','",$locations);
$sql = "select OfficeID, OfficeTitle from Office WHERE location in ('$locations')";
$offices = explode(",", $locations);
$loc = implode("','", $offices);
This helps is creating the variable $loc to location1','location2',location3
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('$loc')");
This creates the mysql query to be:
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('location1','location2',location3')");, which solves the purpose for now.
SELECT OfficeID, OfficeTitle FROM Office WHERE OfficeID IN ( $locations ); ??
Also, look up mysql_real_escape_string and 'separation of concerns`

'Counting' the number of records that match a certain criteria and displaying the numbers (using PHP and MySQL)

I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.

Categories