Multiple MYSQL: PHP loops not working - php

I've been writing some code that essentially collects information based on schools and the user search input. Once the information is pulled up, I also query a database containing users to show how many are signed up at each school, and then another database containing files showing how many files have been uploaded from each school.
I imagine this would require a three tiered loop? If I query the school database and then the student database in succession it works great (Every school will have the appropriate number of students signed up displayed). However the problem is with the files. If I add in the file query, it will only show the first two results of the schools.
This leads me to believe that the file database query isn't correct and after testing a two tiered loop (this time will files instead of students) it appears to be the case. So, what am I doing wrong with the file database code? I copied it directly from the student database code so I haven't a clue why this one won't work. Here is the code that works:
mysql_select_db($database_geographic, $geographic);
$query_school = "SELECT * FROM geographic.school WHERE countryid='$countryid' AND stateid='$stateid' ORDER BY school_name ASC";
$school = mysql_query($query_school, $geographic) or die(mysql_error());
$totalRows_schools = mysql_num_rows($schools);
while ($row_school = mysql_fetch_assoc($school)) {
echo $row_school['school_name'];
echo $row_school['city_name'];
echo $row_school['state_name'];
echo $row_school['schoolid'];
$schoolid = $row_school['schoolid'];
mysql_select_db($database_user_information, $user_information);
$query_users = "SELECT COUNT(*) AS studentcount FROM users WHERE school_name= '$schoolid'";
$users = mysql_query($query_users, $user_information) or die(mysql_error());
while ($row_users = mysql_fetch_assoc($users)) {
echo $row_users['studentcount']; }
But if I throw in this third files loop statement it will not work.
mysql_select_db($database_files, $files);
$query_files = "SELECT COUNT(*) AS filecount FROM file_data WHERE school_id= '$schoolid'";
$files = mysql_query($query_files, $files) or die(mysql_error());
while ($row_files = mysql_fetch_assoc($files)) {
echo $row_files['filecount']; }
}
If I use the file query in place of the student query it will not work either. The problem must be with the file query but I can't figure it out. Any help would be awesome! Thanks!

Related

Alternate to mysqli_num_rows for this php script

I know this has been asked a lot but I can't find no other method that does not relate to num_rows I basically want to see if a record a exist in the database in a if else statement and in other words I don't mind using it but for personal complicated reasons I need to stay away from that because it conflicts on other things I want to add down the road. So this is my code example is there another way to do this with out using mysqli_num_rows?
<?php
$servername='localhost';
$username='angel';
$password='1234';
$db_name='test';
$connect= new mysqli($servername,$username,$password,$db_name);
$query="SELECT*FROM members WHERE first_name='bob'";
$result= $connect->query($query);
if($result->num_rows >0){
echo 'Exist';
}
else{
echo 'Does not exist';
}
?>
just to fill in the options pool
$query = "SELECT id FROM members WHERE first_name='bob'";
then check you get an id returned; assuming the table has an id column, if not just use another one
You could issue a separate query where all you do is count the results:
$getCount = "SELECT COUNT(*) AS `MemberCount` FROM members WHERE first_name='bob'";
Then use the results to determine your program's path.

PHP: Automated data insertion to two connected tables from one form

So, I've been looking for a solution to my case, but I've kept finding only partial and not quite solving-the-matter kind of answers.
First, let me describe what I'm trying to achieve.
In my database I have two tables: PLACES and PLACES_CATEGORIES which are connected by a third table PLACES_A_CATEGORIES in an entity many to many. That is because a PLACE can be characterised by one or more CATEGORIES (but it can also have no CATEGORIES at all).
I want to add data send in one form to two tables: PLACES and PLACES_A_CATEGORIES. The user has all the categories listed with checkboxes and he may (but doesnt have to) check one or more of them.
I automated the display of those checkboxes so it reacts accordingly to changes in database (like adding or removing categories). This part works just fine, but let me show the code for you as it may be useful in solving the real issue:
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
echo "Categories of places:";
for ($j = 0; $j < $category_no; ++$j)
{
$category = $result->fetch_assoc()['name'];
echo '<br><input type="checkbox" id="'.$category.'" name="places_categories" value="'.$category.'"><label for="'.$category.'">'.$category.'</label><br>';
}
So, let's return to the problem. I want to:
always add data (only one row) to the table PLACES
add as many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
So, let me now show you how I've tried to solve the matter and below I'll explain what and why I've done.
if ($everything_OK==true)//Hurra, everything is ok, lets add the place to the database
{
mysqli_query($connection, "SET NAMES utf8");//need it for special characters
//Adding multiple rows of data to database
$query = "SELECT name FROM places_categories";
$result = $connection->query($query);
$category_no = $result->num_rows;
for ($j = 0; $j < $category_no; ++$j)
{
$category[$j] = $result->fetch_assoc()['name'];
if ($_POST['places_categories'] == $category[$j])
{
//counts number of records in table PLACES
$query1 = "SELECT name FROM places";
$result1 = $connection->query($query1);
$places_no = $result1->num_rows;
$places_no += 1;
//looks for category_id in table places_categories where the name matches the current value from form
$query2 = "SELECT category_id FROM places_categories WHERE name='$category[$j]'";
$result2 = $connection->query($query2);
$what_category_id = mysqli_fetch_array($result2);
$connection->query("INSERT INTO places_a_categories VALUES ('$places_no', '$what_category_id')");
}
}
if ($connection->query("INSERT INTO places VALUES (NULL, 0, 0, 0, '$name', '$wysokosc', '$zajawka', '$zatloczenie', '$data_dodania', '$data_edycji', '$szer_geo', '$dlu_geo', '$tytul', '$opis', '$adres', '$tresc')"))
{
echo "Test!";
}
else
{
throw new Exception($connection->error);
}
}
Okay, explanations:
The part which inserts data to the table PLACES works just fine. It
adds data to the database according to what user has added in a form.
No help needed here.
Because of the before-mentioned automation of
table CATEGORIES I want to check how many of categories actually are
in the database. The first part of the code was supposed to do this.
with instruction FOR I assign every existing category to an array with a value equal to the name of the category in the database
then with instruction IF I want to add ass many rows of data to the table PLACES_A_CATEGORIES as many checkboxes have been checked
first value $places_no equals to id of the place which is being added to another table
second value $what_category_id looks for category_id in table PLACES_CATEGORIES where the name matches the current value got from the checkbox
And what are the results? Data is added to the table PLACES with no problem at all. But there is nothing added to the second table. Furthermore, I get no error message of any kind. It's probably some stupid error I just can't see... Any ideas? What have I done wrong?

Problems with table values in SQL queries

OK so I used some php/SQL scripts that I found online for hosting a March Madness pool website. It was a pain to set up and debug the guys code, but I basically got it working. For some reason the author created a "brackets" table and a "scores" table.
The "brackets" table is much larger and contains variables for: id, name, person, email, time, tiebreaker, and all 63 of the persons game selections. id increments for every bracket. name is actually the name given to the bracket by the creator. person is the persons name. And so on.
For some reason, this guy made a separate table for scoring the brackets. The "scores" table has the variables: id, name, score, and scoring_type.
Sorting through the scripts where the data is actually displayed to the website, I have no idea what the creator was thinking, but pretty much all of the data displayed uses the "scores" table.
My Problem: The scores table doesn't have a variable for the persons name. So the rankings and brackets are all displayed and organized by the name that the person gave their bracket. People keep asking me whose bracket is whose. I figured it'd be a quick fix to implement it, but boy was I wrong. I'm new to MySql and don't really completely understand what I'm doing. But I looked some stuff up and I've tried many things and CANNOT get it to work.
What I've tried: I was thinking about combining the tables into one but I didn't want to spend hours on something I set up once a year. Figuring both tables have 2 values that are the same, name and id, I tried doing some queries to match the values and request the variable "person." None of these have worked however.
I modified this in a few different ways:
$query = "SELECT person FROM `brackets' WHERE name='$name'";
$result = mysql_query($query,$db) or die(mysql_error());
echo "mysql_result($result)";
I tried with and without using variables. I also tried:
$query = 'SELECT * FROM `brackets';
$result = mysql_query($query,$db) or die(mysql_error());
$dataArray = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$dataArray[] = $row; // add the row in to the results (data) array
}
$personsNameToDisplay = personsName($name, $dataArray);
echo "$personsNameToDisplay";
With a function that I also tried several approaches with:
function personsName( $passedBracketName, $dataArray ){
$personsMatchedName;
foreach ($dataArray as $key => $value){
if($value == $passedBracketName ){
$personsMatchedName = $value['person'];
}
}
return $personsMatchedName;
}
The error that I've been getting is:
Table 'mlmadness.brackets' WHERE name='beasters'' doesn't exist
Yet when I go into mySQL, and click on "brackets" then "name" there is definitely a bracket with the name value of "beasters"
Thanks
"SELECT person FROM 'brackets' WHERE name='{$name}'";
that should do the trick. You also had blasters' .. the closing should also be and not a '
Better Way:
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$query = "SELECT person FROM brackets WHERE name='{$name}'";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
var_dump($row);
}

Include within a while loop

I'm sure my inability to solve this problem steams from a lack of knowledge of some aspect of php but I've been trying to solve it for a month now with no luck. Here is a simplified version of the problem.
In my database I have a members table, a childrens table (the children of each member), and a friend requests table (this contains the friend requests children send to each other).
What I'm attempting to do is display the children of a particular parent using the following while loop....
$query = "SELECT * From children " . <br>
"WHERE parent_member_id = $member_id"; <br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_children = mysql_num_rows($result);<br>
echo $num_children;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
<div>echo $first_name<br>
}
This while loop works perfectly and displays something like this...
1) Kenneth
2) Larry
What I'm attempting to do though is also display the number of friend requests each child has next to their name...like this
Kenneth (2)
Larry (5)
To do this I attempted the following modification to my original while loop...
$query = "SELECT * From children " .<br>
"WHERE parent_member_id = $member_id";<br>
$result = mysql_query($query) <br>
or die(mysql_error());<br>
$num_movies = mysql_num_rows($result);<br>
echo $num_movies;<br>
while($row = mysql_fetch_array($result)){<br>
$first_name = $row['first_name'];<br>
$child_id = $row['child_id'];<br>
echo $first_name; include('counting_friend_requests.php') ;
}
In this version the included script looks like this...
$query = "SELECT <br>children.age,children.child_id,children.functioning_level,children.gender,children.parent_member_id,children.photo, children.first_name,friend_requests.request_id " .
"FROM children, friend_requests " .
"WHERE children.child_id = friend_requests.friend_two " .
"AND friend_requests.friend_one = $child_id"; <br>
$result = mysql_query($query)<br>
or die(mysql_error());<br>
$count = mysql_num_rows($result);<br>
if ($count==0)<br>
{<br>
$color = "";<br>
}<br>
else<br>
{<br>
$color = "red";<br>
}<br>
echo span style='color:$color' ;<br>
echo $count;<br>
echo /span;<br>
Again this while loop begins to work but the included file causes the loop to stop after the first record is returned and produces the following output...
Kenneth (2)
So my question is, is there a way to display my desired results without interrupting
the while loop? I'd appreciate it if anyone could even point me in the right direction!!
Avoid performing sub queries in code like the plague, because it will drag your database engine down as the number of records increase; think <members> + 1 queries.
You can create the query like so to directly get the result you need (untested):
SELECT child_id, first_name, COUNT(friend_two) AS nr_of_requests
From children
LEFT JOIN friend_requests ON friend_one = child_id OR friend_two = child_id
WHERE parent_member_id = $member_id
GROUP BY child_id, first_name;
It joins the children table records with friend_requests based on either friend column; it then groups based on the child_id to make the count() work.
You don't need to include the php file everytime you loop. Try creating a Person class that has a method getFriendRequestCount(). This method can all the database. This also means you can create methods like getGriendRequests() which could return an array of the friend requests, names etc. Then you could use count($myPerson->getFriendRequests()) to get the number. Thousands of options!
A great place to start, http://php.net/manual/en/language.oop5.php
Another example of a simple class, http://edrackham.com/php/php-class-tutorial/
Eg.
include ('class.Person.php');
while(loop through members)
$p = new Person(member_id)
echo $p->getName()
echo $p->getFriendRequestCount()
foreach($p->getFriendRequests as $fr)
echo $fr['Name']
In your Person class you want to have a constructor that grabs the member from the database and saves it into a private variable. That variable can then be accessed by your functions to proform SQL queries on that member.
Just to clarify whats happening here.
"include" processing is done when the script is parsed. Essentially its just copying the text from the include file into the current file. After this is done the logic is then parsed.
You should keep any include statements separate from you main logic. In most cases the "include"d code will contain definitions for one or more functions. You can then call these functions from the main body of your program at the appropriate place.

text input (seperated by comma) mysql input as array

I have a form where I am trying to implement a tag system.
It is just an:
<input type="text"/>
with values separated by commas.
e.g. "John,Mary,Ben,Steven,George"
(The list can be as long as the user wants it to be.)
I want to take that list and insert it into my database as an array (where users can add more tags later if they want). I suppose it doesn't have to be an array, that is just what seems will work best.
So, my question is how to take that list, turn it into an array, echo the array (values separated by commas), add more values later, and make the array searchable for other users. I know this question seems elementary, but no matter how much reading I do, I just can't seem to wrap my brain around how it all works. Once I think I have it figured out, something goes wrong. A simple example would be really appreciated. Thanks!
Here's what I got so far:
$DBCONNECT
$artisttags = $info['artisttags'];
$full_name = $info['full_name'];
$tel = $info['tel'];
$mainint = $info['maininst'];
if(isset($_POST['submit'])) {
$tags = $_POST['tags'];
if($artisttags == NULL) {
$artisttagsarray = array($full_name, $tel, $maininst);
array_push($artisttagsarray,$tags);
mysql_query("UPDATE users SET artisttags='$artisttagsarray' WHERE id='$id'");
print_r($artisttagsarray); //to see if I did it right
die();
} else {
array_push($artisttags,$tags);
mysql_query("UPDATE users SET artisttags='$artisttags' WHERE id='$id'");
echo $tags;
echo " <br/>";
echo $artisttags;
die();
}
}
Create a new table, let's call it "tags":
tags
- userid
- artisttag
Each user may have multiple rows in this table (with one different tag on each row). When querying you use a JOIN operation to combine the two tables. For example:
SELECT username, artisttag
FROM users, tags
WHERE users.userid = tags.userid
AND users.userid = 4711
This will give you all information about the user with id 4711.
Relational database systems are built for this type of work so it will not waste space and performance. In fact, this is the optimal way of doing it if you want to be able to search the tags.

Categories