Populate list based on data entered - php

I have a form which has a postcode field (text) and a school field (selection) and what i am trying to do is to populate the selection field with schools from a database :
<?php
$conn = mysqli_connect("localhost", "twa312", "dam6av9a");
mysqli_select_db(twa312, $conn)
or die ('Database not found ' . mysqli_error() );
</form>

Have you worked with joins in SQL before? You can do a select without them, but its much cleaner/faster/easier.
You'd do something like:
SELECT school_info.name AS name, local_schools.postcode AS postcode FROM school_info INNER JOIN local_schools ON local_schools.schoolID = school_info.schoolID
This will grab everything from both tables where your ID is matched.
Give that a try. Your PHP array should end up the same. $var['name'] and $var['postcode']

Related

selecting information from 2 tables returns error

I do something like this
<?php
require_once('inc/config.php');
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot Connect : '.mysqli_error());
$sql = "select username from education_info,profile_info where username ='j_spaxx22'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) )
{
echo $row['fullname'] ."". $row['email'] ."". $row['city'] ."". $row['state'] ."". $row['lga'] ."". $row['inst_name'] ."". $row['study_course'];
}
?>
And I get this Error
Error: Column 'username' in field list is ambiguous
What am I getting wrong?
Edit:
When i do a Query like this
$sql = "select * from education_info,profile_info";
I get all the tables correctly
but when i do something like this
$sql = "select username from education_info,profile_info where username ='j_spaxx22'";
I get an Error, what do i seem to be getting Wrong?
use this query and get output with no error just use tablename;
select education_info.username,profile_info.username from education_info,profile_info where education_info.username ='j_spaxx22' and profile_info.username = 'j_spaxx22';
You have 2 columns with the same name username in your tables education_info,profile_info
If you dont need to JOIN the table , simply select from the table you want from
select username
from education_info
where username ='j_spaxx22'
OR
select username
from profile_info
where username ='j_spaxx22'
If you need to JOIN the tables
SELECT profile.username
FROM profile_info profile
JOIN education_info education ON profile.columntojoin=education.columntojoin
WHERE profile.username ='j_spaxx22'
Notice that after each table a ALIAS is given to each table, with that you can say from which table you want to display the data. For instance profile.username. When 2 tables join that have the same columname, they need to be identified with the table name alias also, otherwise you get Column in field list is ambiguous error.
When you use * and no WHERE, MySQL will return the full dataset since it can just display the data as it is, when using filters like WHERE, MySQL has to know which column exactly if they exist in multiple tables.
you can use this query
SELECT username
FROM education_info
WHERE username = 'j_spaxx22'
UNION
SELECT username
FROM profile_info
WHERE username = 'j_spaxx22'
;
Try this.
$sql="select
education_info.username as un, education_info.col2 as c2,
education_info.col3 as c3,
profile_info.username as un2, profile_info.col2 as c4
from education_info LEFT JOIN profile_info ON
education_info.username=profile_info.username
AND profile_info.username ='whatever';";
you should preference the field with the full table name, for example:
if the username field is from education_info table, the sql statement should be:
select education_info.username from education_info,profile_info where education_info.username ='j_spaxx22';

Show certain code depending on mysql query? (php)

I need a little kickstart here.
We're just learning php in school and we have this project where we're making a website for movie browsing. So we wanna be able to select genre, and show all movies from that genre using a MySQL database. We're all clear on the SQL queries and such, my question is rather how I make the browser show movies depending on SQL query?
Let me explain. Say we're movies.com
So on movies.com/genre is where you select the genre right, and on movies.com/display is where you're supposed to see the movies from the genre selected. So, clicking on "Comedy" should take you to movies.com/display and show you only the comedy movies. Selecting "Drama" should take you to the same site (movies.com/display) and show you only the drama movies.
Problem here is that we just don't know where to begin, it became a problem when switching page to show certain sql queries depending on what you selected in a previous page. I am not sure how to Google it, but just a link or a suggestion will help. I'm sure it can't really be too hard.
Thanks in advance.
Start with the html to choose a genre:
<form action="display.php" method="POST">
<select name="genre">
<option value="drama">Drama</option>
<option value="comedy">Comedy</option>
<option value="thriller">Thriller</option>
<option value="horror">Horror</option>
</select>
<input type="submit" value="Submit"/>
</form>
Here we have a form with a dropdown menu to select the genre. The forms action goes to display.php
Create display.php where we can get the submitted value and put that into our query:
// get the submitted value
$genre = $_POST['genre'];
// set a default genre if the POST genre is empty
if(empty($genre)) {
$genre = 'comedy';
}
// connect to database
$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");
// check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: (" . mysqli_connect_errno() . ") ";
}
// build the query
$query = "SELECT * FROM movie WHERE genre = '".$genre."'"; // unsafe !!
$query = "SELECT * FROM movie WHERE genre = '".mysqli_real_escape_string($link, $genre)."'"; // safer
// execute query
$result = mysqli_query($link, $query);
// check result
if (!$result) {
echo 'Query unsuccessfull!';
}
// show values
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'];
echo $row['description'];
echo "<br/>";
}
// close connection
mysqli_close($link);
I would suggest having a table of genres. That way you can display the list of genres easily for a user to select from (ie, you could populate an HTML forms select list from that table). The list of genres would have a unique id (an integer) and a text description, so when the list of produced you display the description but have a value that is the id.
Then have a table of movies (I presume you already have this). Each movie would be identified by a unique integer id field/
Lastly a table of movies to genres. This would just link the id of the movie to the id of the genre(s) for the movie. This way you can have a movie linked to several genres if required.
Doing it this way also means that the values you return from the HTML forms can just be integers, which are easily made safe (just use the php intval() function).
In use you would provide a list of genres as a SELECT list. When the user selects an item and submits the form the id of the selected genre is returned to the script. The script can then do a query that joins the tables together, checking the genre is the selected genre that has been returned to the script.
For example.
tbl_genres
id
genre_name
tbl_movies
id
movie_name
tbl_genre_movie
genre_id
movie_id
Then to get the details for a returned genre id:-
$sql = "SELECT *
FROM tbl_genres
INNER JOIN tbl_genre_movie
ON tbl_genres.id = tbl_genre_movie.genre_id
INNER JOIN tbl_movies
ON tbl_genre_movie.movie_id = tbl_movies.id
WHERE tbl_genres.id = ".intval($_POST['genre_id']);

php MySQL error for retrieving data

I have a PHP code for selecting data from a database, but it produces NULL result, although the same query performed manually works well. Here's relevant part of code:
$conn = mysqli_connect($host,$user,$password);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_db_name($dbName,$conn);
$query = "SELECT Images.Path,p.NameAr,p.DescriptionAr FROM
(SELECT * FROM project where TypeID = 1) as p
JOIN Images where Images.ProjectID = p.ID";
$result = mysql_query($query,$conn);
var_dump($result);
What can be wrong about it?
Not sure about PHP related error but your query formation is not corect.
Change your query like below. Moreover, you are not fetching any column from images table then why do a join with images table?
SELECT Path,NameAr,DescriptionAr
FROM
(
SELECT p.* FROM project p
JOIN
Images i on i.ProjectID = p.ID and p.TypeID = 1
) tab
You use mysqli_connect but then you wrote mysql_* If you fix all mysql_* to mysqli_* it should work.

mulitiple database select php mysql

I have 2 databases on the same server with 2 identical tables.
What I want to do is select all records from both tables and join them in one array.
I've been messing around with the script below. For some reason it returns the records of db2.tbl twice and doesn't return the db1.tbl records at all. When I try to select the data from a single database is works fine for both of them. Does any one see the problem?
<?PHP
require_once("config.php");
$conn = #mysql_connect($dbhost, $dbuser, $dbpass)or die ('Error connecting to mysql server'.mysql_error());
$q = mysql_query("SELECT * FROM db1.tbl JOIN db2.tbl");
var_dump(mysql_num_rows($q));
while($arr = mysql_fetch_assoc($q)){
var_dump($arr);
}
?>
Is this what you want ? All records from database1 followed by all records from database2:
$q = mysql_query("SELECT * FROM db1.tbl UNION SELECT * FROM db2.tbl");
I assume the user you are connecting with has access to both databases.
Your query should work. However add tilt(`) to your database name table name. Execute the query first in mysql see whether it is ok than execute with php.

JSON-PHP/MySQL - Retrieving info from DB

I am using a JSON script ot print out a list of information (later it is sent to my iPhone application, all works fine on that end) with a specific value in a row in my table in my db.
I have managed to do this, however I am looking to expand my search results.
Working Code - obviously i setup
$link = mysql_connect ($host, $uid, $pwd) or die ("Could Not Connect");
mysql_select_db($db) or die("Could Not Connect to Database");
$arr = array();
$rs = mysql_query("SELECT id, story, releasedate, title, youtube, picture FROM movies WHERE category='Action'");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
I guess where line #4 is, at the end of that, I would like to to do the following, but cannot find any sample code for it.
Example Code:
......from Movies WHERE category CONTAINS 'Action'");
that obviously does not work and I get an error, pretty much my category row has multiple values for movies, ie DRAMA,Action Sustepnse etc in one row, as some movies are a mix of categories now a days, and would like it filtered out properly without the hassle of adding addition category rows in my db
you can do this
this will select movies that belong to one of these genres
WHERE category IN ('action', 'horror', 'comedy')
but if you want to search if the category contains action or drama or horror you need
WHERE category LIKE '%Action%' OR category LIKE '%Drama%'...

Categories