Guidance with multiple PHP queries - php

I'm trying to display the results from 3 separate queries in 3 adjacent <div> containers. The three queries are as follows:
$query="SELECT * FROM students WHERE WeekOne='employer'";
$query="SELECT * FROM students WHERE WeekTwo='employer'";
$query="SELECT * FROM students WHERE WeekThree='employer'";
Desired output:
WEEK ONE ----- WEEK TWO ----- WEEK THREE
Result 1 ---------- Result 1 ----------- Result 1
Result 2 ---------- Result 2 ----------- Result 2
(etc...)
Can anybody help me with this? I've seen the multi_query on PHP manual but have no idea how to implement this. Many thanks.
#Emmanuel G
<?
$user = "xx";
$user_password = "xx";
$db_name = "xx";
$db = new mysqli ("xx", $user, $user_password, $db_name);
$queries = array(
"SELECT * FROM students WHERE WeekOne='$Name'",
"SELECT * FROM students WHERE WeekTwo='$Name'",
"SELECT * FROM students WHERE WeekThree='$Name'"
);
// iterate through the queries and their results
foreach($queries as $query){
$result = $mysqli->query($query);
echo '<div>'; // open that div up
while($row = $result->fetch_assoc()){ // gives u an array hoorah!
echo '<pre>'.print_r($row, true).'</pre>'; // just to look at it
echo "<p>{$row['FirstName']}</p>"; // just an example
}
echo '</div>'; // close it up
}
?>

The easiest way is change the query to this:
$query="SELECT * FROM students WHERE WeekOne='employer' OR WeekTwo='employer' OR WeekThree='employer'";
And then format the output accordingly.

Yes, change your query to bring your all result in one query request, then you manipulate from the data result, hitting multiple time for simple answer to the server is not a best practice, because your query is very simple.
but for your question
multi_query($query) //you can use this
have a look here http://suite101.com/article/how-tor-run-multiple-mysql-queries-with-php-a105672

To display it just iterate over each individual result and place that into a div. To make them adjacent you would add some css to your div's to float them since divs are inherently block elements and don't line up horizontally without some help.
Assuming you already have your database connection set up and should be using mysqli or the such you could generate your markup like so:
// u should try to make this one query but that's irrelevant to the question
// so I'll leave that to you to do later
$queries = array(
"SELECT * FROM students WHERE WeekOne='employer'",
"SELECT * FROM students WHERE WeekTwo='employer'",
"SELECT * FROM students WHERE WeekThree='employer'"
);
// iterate through the queries and their results
foreach($queries as $query){
if($result = $mysqli->query($query)){// only do stuff if you get a result
echo '<div>'; // open that div up
while($row = $result->fetch_assoc()){ // gives u an array hoorah!
echo '<pre>'.print_r($row, true).'</pre>'; // just to look at it
echo "<p>{$row['data']}</p>"; // just an example
}
echo '</div>'; // close it up
// mysqli free the result to prep for the next one
$result->free();
} else {
echo "Query failed to return results:\n$query\n";
}
}

i am guessing you are passing employer as URL parameter , so in either way you can also pass which week you want to compare with, let's say
$week = $_GET['weekOne'];
$employer = $_GET['employer'];
$query="SELECT * FROM students WHERE $week= $employer";
make sure you escape your data before executing query,to avoid sql injections
i hope it will help you. Thanks

Related

Empty array in PHP with MySql

I am trying to code it so users can type in their -- or others -- usernames which will be converted in their UUID then returns that user's stats from my MySql databse.
The code I attempted this with is
$username = $_POST['searchbox'];
$json = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$username);
$obj = json_decode($json);
$id = $obj->id;
$rank = Database::query("SELECT * FROM playerdata WHERE uuid=:uuid", array(':uuid'=>"".$id))[0]['rank'];
echo 'Showing results for '.$_POST['searchbox'].' '.$id.' Rank: '.$rank;
Except when I run this code it outputs:
"Showing results for kingbluesapphire 0d8d246d11c54cbbb197c6bc8ba01ee2 Rank:"
I know it's not a problem with the connection to the database because other queries are working
My goal right now is to get the field in the MySql Database thats called rank and I would like to display their rank.
Given the discussion in the comments, either you have to find out what is removing the dashes which I highly recomend to or change your query to:
$rank = Database::query("SELECT *
FROM playerdata
WHERE replace(uuid, '-','')=:uuid",
array(':uuid'=>"".$id))[0]['rank'];
Databases need to be given the exact value you are looking for, any different character in a equals operation will not give you any data.
It's more like:
<?php
if(isset($_POST['searchbox']){
$sb = $_POST['searchbox']);
$json = json_decode(file_get_contents("https://api.mojang.com/users/profiles/minecraft/$sb"));
if($queryRes = $connection->query("SELECT * FROM playerdata WHERE uuid={$json->id}")){
if($queryRes->num_rows){
$o = $queryRes->fetch_object(); // guessing there's only one row or you would put this in a while loop
echo "Showing results for $sb {$o->uuid} Rank:{$o->rank}";
}
}
else{
die($connection->connect_error);
}
}
?>
I'm assuming uuid is a number. Do tell.

PHP multiple entries

I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}

php pdo two nealry similar selects

I´m trying to get uses to the PHP PDO Syntax. Maybe somone can have a look at this peace of code. It seems it´s a bit much lines for little effort.
I catch a User Post-Input (ID). Know I need for calculation reason the values BejagFlach from all Users (the sum of them) and the single value BejagFlach from the User identified by the ID. Do I need two querys for this like here? or is there are shorter/better way?
/* Fetch POST Data */
$User_Num = $_POST['User_Num'];
/* Build query for one User */
$dbSelect = $objDb->prepare("SELECT BejagFlach,Name FROM Benutzer WHERE lfdNr = :User_Num");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect->execute(array(':User_Num' => $User_Num));
/* Build query for all Users */
$dbSelect2 = $objDb->prepare("SELECT BejagFlach FROM Benutzer");
$dbSelect2 -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect2->execute();
/* Output + Calculate */
while($row = $dbSelect->fetch()) {
$totalUser += $row['BejagFlach'];
$who = utf8_encode($row['Name']);
}
/* Output + Calculate */
while($row = $dbSelect2->fetch()) {
$totalAll += $row['BejagFlach'];
}
Kind regards,
toni
Since you need at least your second query, I would do like this so you do only 1request to the database :
$dbSelect = $objDb->prepare("SELECT BejagFlach,lfdNr FROM Benutzer");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect ->execute();
while($row = $dbSelect->fetch()) {
$totalAll += $row['BejagFlach'];
if( $row['lfdNr'] == $UserNom) {
$totalUser += $row['BejagFlach'];
$who = utf8_encode($row['Name']);
}
}
No, it doesn't seem too much?
The only thing I would change, is if you are only after the number of records matched, use rowCount
<?php
$sel = $dbh->prepare('select * FROM fruit');
$sel->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were selected:\n");
$count = $sel->rowCount();
print("Seleted $count rows.\n");
?>

How do I get the first and last results from a query?

I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that - you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
You should ask DB to get count of the rows, not using mysql function, it's far more effective, so use SELECT count(*) FROM mytable.
For $pages use ceil() as you want all rows to be printed, if you have $max 5 and have 11 rows, round will make $pages 2, where you actually want 3 (last page just contains that last 11th row)
in LIMIT you want to LIMIT row_count OFFSET offset. You can calculate offset from page number, so: $max = row_count but $offset = ($max * $page) - $max. In your code if $get is directly the page, it means you get $get'th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)
I have prepared simple example here which uses PDO, maybe that gives you idea how simple it's use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state, 'SELECT * FROM pseudorows LIMIT '.$start.','.$max by I wanted to make an example how easy it is (and then safe):
// DB config
$DB_NAME = 'test';
$DB_USER = 'test';
$DB_PASSWD = 'test';
// make connection
try {
$DB_CONN = new PDO("mysql:host=localhost;dbname=".$DB_NAME, $DB_USER, $DB_PASSWD);
$DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e);
}
// lets say user param 'p' is page, we cast it int, just to be safe
$page = (int) (isset($_GET['p'])?$_GET['p']:1);
// max rows in page
$max = 20;
// first select count of all rows in the table
$stmt = $DB_CONN->prepare('SELECT count(*) FROM pseudorows');
$stmt->execute();
if($value = $stmt->fetch()) {
// now we know how many pages we must print in pagination
// it's $value/$max = pages
$pages = ceil($value[0]/$max);
// now let's print this page results, we are on $page page
// we start from position max_rows_in_page * page_we_are_in - max_rows_in_page
// (as first page is 1 not 0, and rows in DB start from 0 when LIMITing)
$start = ($page * $max) - $max;
$stmt = $DB_CONN->prepare('SELECT * FROM pseudorows LIMIT :start,:max');
$stmt->bindParam(':start',$start,PDO::PARAM_INT);
$stmt->bindParam(':max', $max,PDO::PARAM_INT);
$stmt->execute();
// simply just print rows
echo '<table>';
while($row = $stmt->fetch()) {
echo '<tr><td>#'.$row['id'].'</td><td>'.$row['title'].'</td></tr>';
}
echo '</table>';
// let's show pagination
for($i=1;$i<=$pages;$i++) {
echo '[ '.$i.' ]';
}
}
mysql_fetch_array returns an associative array
Which means you can use reset and end to get the first and last results:
$pqa = mysql_fetch_array($pq);
$first = reset($pqa);
$last = end($pqa);
I don't see how you plan to use the actual results, just page numbers should be sufficient for pagination.
Still, hope it helps. And yes, upgrade to mysqli, so your code doesn't get obsolete.

php query does not retrieve any data?

well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {

Categories