need help creating a mysql query - php

Let's assume I a have a table called "users" which has the following relevant columns:
username
zipcode
Let's also assume I have a table called "shops" which has the following relevant columns:
shop_name
zipcode
Let's also assume I have a table called "preferred_shops" which has the following relevant columns:
shop_name
username
Let's also assume I have a table called "zipData" which has the following relevant columns:
zipcode
lat
lon
Currently I can run this code with success:
$lat="49.886436"; // Value should be obtained from the zipData table by doing a "SELECT FROM zipData WHERE zipcode=(users_zip_code)" or similar query
$lon="-97.14553"; // Value should be obtained from the zipData table by doing a "SELECT FROM zipData WHERE zipcode=(users_zip_code)" or similar query
$radius=5;
$query="SELECT zipcode FROM zipData
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+
POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius)";
The query above will successfully display all the other zip codes that are within the given radius of the supplied lat/lon but I have no interest in knowing what other zip codes there are... I want to know what shops are within the radius.
Any help you can give would be greatly appreciated.
==== Edited because I realized it is actually a little more complex ====
This is what I need to do...
Retrieve the user's zipcode from "users" table
Find the user's lat/lon from the zipData table
Find all the shops within a given radius that is also in a "preferred_shops" table with the given user in the "username" column
Problems to consider: the zipcode in "zipData" has no white space but the zipcodes in "users" and "shops" have white space for cosmetic reasons... such as Canadian Postal codes which are in the "A1A 1A1" format
==== Edited to post solution ====
The system says I am not allowed to answer my own question. That sounds strange since with the help of others I already found the answer. As a work around I am editing the original post. Here is the solution...
Ok so I figured it out (with the help of the people that replied)... This is what I did.
IT LIKELY COULD BE A LOT SHORTER AND CLEANER SO PLEASE FEEL FREE TO MAKE IT BETTER IF YOU KNOW A BETTER WAY.
$query = "SELECT * FROM preferred_shops
WHERE `username`='{$_SESSION['account_name']}'
";
$result = mysql_query($query);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
// Get user's preferences and postal code
$query2 = "SELECT * FROM seekers
WHERE `username`='{$_SESSION['account_name']}'
";
$result2 = mysql_query($query2);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows2 = mysql_num_rows($result2);
$row2 = mysql_fetch_array($result2);
$radius=$row2['radius']; // Didn't mention that is column was in the table but that didn't matter... the value could have come from anywhere.
// Get user's lat/lon
// Remove white space from the postal code
$query3="SELECT * FROM zipData WHERE zipcode=replace('{$row2['postal']}',' ','')";
$result3 = mysql_query($query3);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows3 = mysql_num_rows($result3);
$row3 = mysql_fetch_array($result3);
$lat=$row3["lat"];
$lon=$row3["lon"];
$query4="SELECT shop_name FROM zipData,shops
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius)
AND replace(shops.zipcode,' ','') = zipData.zipcode
AND shops.shop_name={$row['shop_name']}
";
$result4 = mysql_query($query4);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows4 = mysql_num_rows($result4);
$num_jobs=$num_rows4;
$i=0;
while($row4 = mysql_fetch_array($result4))
{
$shopArray[$i]=$row4["shop_name"];
$i++;
}
var_dump($shopArray);
}

You need to join to the shops table
SELECT shop_name FROM zipData,shops
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+
POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius) and
shops.zipcode = zipdata.zipcode

select shopname from shops where zipcode in ( <your other working query> )

Related

How to grab an int from my MySQL server via PHP?

I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.

Eloquent calls in Laravel 4: Dealing with single columns over multiple tables

I'm back with another Laravel issue that I can't seem to crack with my procedural PHP, direct mysql_query background. It basically involves the Eloquent ORM over multiple tables.
I have 3 tables (Users, User_Profiles, and User_Answers). The Users table only keeps the very basics of the user (auto_incremented id, email, password), the User_Profiles table contains a few more details (image url, country, city, gender, etc) and belongs_to the User model. The User_Answers table is a list of answers given by the user and also belongs_to the User model.
What I would like to do is select all rows from the User_Profiles table where the city is the same as the city of the logged-in user, get their user_id's in an array and then compare the answers (from the User_Answers table) to the answers of the currently logged in User. The following is what I'm looking to do but in plain PHP and (for explanation purposes only) mysql_query. I apologize in advance for the awful code. I just need to be pointed in the right direction.
<?php
$link = mysql_connect("localhost", "xxx", "xxx");
$db = mysql_select_db('testersize', $link);
$id = 2;
$sql = "SELECT city FROM user_profiles WHERE user_id = $id";
$query = mysql_query($sql, $link);
$row = mysql_fetch_row($query);
$city = $row[0];
echo $city . "</br>";
$sql = "SELECT user_id FROM user_profiles WHERE city = '$city'";
$matches = mysql_query($sql, $link);
//
while($row = mysql_fetch_row($matches)){
$u_id = $row[0];
$sql = "SELECT books, movies, music FROM user_answers WHERE user_id = $u_id";
$query2 = mysql_query($sql, $link);
$row2 = mysql_fetch_row($query2);
echo "<h2>User Number: " . $u_id . "</h2>";
echo "your favorite books:" . $row2[0] . "</br>";
echo "your favorite movies:" . $row2[1] . "</br>";
echo "your favorite music:" . $row2[2] . "</br>";
}
?>
$user_profiles = User_Profiles::where('city','=',Auth::user()->city)->get();
foreach($user_profiles as $user_profile){
$id = array('user_id'=>$user_profile->user_id);
}
So that code will get you the user_profiles by city and then loop through them and put their in an array , im not sure what do you mean by match answers to users table though..
$user_ids = User_Profiles::where('city','=',Auth::user()->city)->lists('user_id');
$favorites = User_Answers::whereIn('user_id',$user_ids)->get();
foreach($favorites as $favorite)
{
echo $favorite->book;
echo $favorite->music;
echo $favorite->movie;
}

Search for form element in database multiple times

I am trying to learn php and came across a task which i have need help with.
Background information - I have a postgresql database which has
multiple tables.
What I need - When I enter anything in the form on my HTML page, i
need to extract all information from all the tables that contain
information related to what I have entered.
Example - Suppose I enter food poisoning in the form. I need to access
all the tables and extract the different information related to food
poisoning.
My code: (the connection part is not being posted as it works fine)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.bacteria WHERE disease = $1');
// if (pg_numrows($result) == 0) {
// $result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.virus WHERE disease = $1');
// }
//$sql = "SELECT * FROM Project.bacteria WHERE disease=";
//$result = pg_query($dbh, $sql);
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
?>
For the above code, when I enter food poisoning it searches just one table i.e bacteria and returns the related information ( here as a test i have taken just information at row position 1 and row position 2.)
Since there are multiple tables, like a table drugs that stores information of drugs used to cure food poisoning, i would want to extract that information from the respective table.
Any help would be appreciated.
try this one
SELECT * FROM bacteria WHERE disease = ''
UNION ALL
SELECT * FROM drugs where desease = ''
but i think the best way is to normalize you tables. :)

An instructor retrieves the student who are enrolled in the course he/she teaches

I am building a simple website that helps students and instructors in universities.
I am facing a problem about the following query:
An instructor retrieves the students' IDs and names who are enrolled in the course he/she teaches.
I have the following tables, followed by their fields:
Enrollment (CourseCode - StudentID - Grade)
Studnet (ID - Name)
As you can see the only connector between the two tables is the student ID.
The code that I wrote is
<?
session_start();
$COCODE = $_SESSION['GlobalCode'];
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$COCODE' ") ;
$row11 = mysql_fetch_array($result11);
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Student where StudentID= '$StID' ") ;
echo "<table border cellpadding=3>";
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
echo "</table>";
?>
What I am trying to do is to retrieve the course code from the Enrollment table and then retrieving the students names through the ID.
The problem is that I got the following message:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
I hope you can help me solving the problem.
Thanks
Have you tried to narrow down which of the queries is causing the problem? That would be your first step. Some other pointers:
you need to check that each SQL query is successful and returning a valid value before using it in the next query... otherwise that query will cause an error.
Try using: mysql_query ($your_query) or die ('Error: '.mysql_error ()); for each query for a more detailed error message. (for debugging only, not for production)
That error usually means there's something wrong with your query, or perhaps you are not connected to your database. If its the first problem, try changing your query to this:
$result11 = mysql_query("SELECT * FROM `Enrollment` WHERE `CourseCode` = '$COCODE' ");
Otherwise, check your database connection.
Finally, I solved it.
I did the following changes:
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$InstID' ") or die ('Error: '.mysql_error ());
echo "<table border cellpadding=3>";
while($row11 = mysql_fetch_array($result11))
{
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Students where ID = '$StID' ") or die ('Error: '.mysql_error ());
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
}
echo "</table>";
mysql_close($con);
?>
Thanks

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Categories