Integrating a INNER JOIN into an existing PHP function (PHP/MySQL) - php

I have an inner join working when used in SQL, however when I try to integrete it into a function in my PHP it gives me a syntax error of "unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)". The code is as follows:
echo "<table border=='1'>
<tr>
<th>Name</th>
<th>Exam Date</th>
<th>Level</th>
<th>Mark</th>
<th>Style</th>
</tr>";
while($row = mysql_fetch_array($exam_recordation))
{
echo "<tr>";
$name_query = mysql_query("SELECT DISTINCT student.name
FROM student
INNER JOIN exam ON student.email = exam.Student_email
WHERE student.email <> $row['Student_email']");
while($row = mysql_fetch_array($name_query))
{
echo "<td>" . $row['name'] . "</td>";
}
echo "<td>" . $row['examDate'] . "</td>";
echo "<td>" . $row['level'] . "</td>";
echo "<td>" . $row['mark'] . "</td>";
echo "<td>" . $row['style'] . "</td>";
echo "</tr>";
}
echo "</table>";
The reason I have the inner join there is because it requires Student_email from out of $exam_recordation for each record that it goes through. $exam recordation holds all records from the exam table that met the set conditions. I've seen from my own research that nesting queries is not the best thing to do, I don't think I am nesting queries but I am nesting while loops which to me looks to be suspiciously dangerous/bad practice. Its the only way I know how to perform this sort of function/operation.
The help I need is in working out how to get that inner join into that function. The inner join takes the name out of the student table for each email of each record that the first while loop goes through and echo's it in.

Basic PHP syntax: array keys in a double-quoted string can NOT be themselves quoted. e.g.
$arr = "This is an $array['reference']."
^-- ^-- incorrect
It should be either:
$arr = "This is an {$array['reference']}."; // note the {} notation
or
$arr = "This is an $array[reference]."; // Note lack of quotes.

Before I start, please note that mysql_ has officially become deprecated. You should move on to mysqli or pdo.
You might be closing your while loop before you originally intended... see below comments
while($row = mysql_fetch_array($name_query))
{
echo "<td>" . $row['name'] . "</td>";
} << REMOVE THIS
echo "<td>" . $row['examDate'] . "</td>"; << PHP NO LONGER KNOWS ABOUT $row
echo "<td>" . $row['level'] . "</td>";
echo "<td>" . $row['mark'] . "</td>";
echo "<td>" . $row['style'] . "</td>";
echo "</tr>";
}
You might also want to ensure that PHP is able to replace your query variable. MySQL will also need to see quotes around a string of text to make the comparison.. Try changing concatenating your query to...
$name_query = mysql_query("SELECT DISTINCT student.name
FROM student
INNER JOIN exam ON student.email = exam.Student_email
WHERE student.email <> '{$row['Student_email']}'");

Related

can we simplify "while" inside of "while"?

i need some little help ,,,
I have a data like this.., (I use php mysql)
Initially there was no problem with this, but as time goes by, my data is getting bigger and bigger.
finally its made my program slow ..
I think maybe because I used "while" inside of "while". make SQL is called multiple times.
is there a solution to make it faster ??
I have hundreds of data in tb1 and thousands in tb2 T.T
You should not be using loops to iterate over tables. SQL is an inherently set based declarative language. So, you should just join the tables, order the result set, and then use a single loop with presentation logic. Use this query:
SELECT tb1.id_a, tb2.id_b, tb2.data
FROM tb1
INNER JOIN tb2 ON tb2.id_a = tb1.id_a
Then, use this PHP script:
echo "<table>";
echo "<tr><th>No.</th><th>id_b</th><th>data</th></tr>";
$a = null;
while ($row = mysql_fetch_array($result)) {
if ($a == null || $row['id_a'] != $a) {
echo "<tr>";
echo "<td>" . $row['id_a'] . "</td>";
echo "<td colspan=2>data" . $row['id_a'];
echo "</tr>";
$a = $row['id_a'];
}
echo "<tr>";
echo "<td></td>";
echo "<td>" . $row['id_b'] . "</td>";
echo "<td>" . $row['data'] . "</td>";
echo "</tr>";
}
echo "</table>";

How to escape SELECT COUNT (*) and create a table

I am fairly new to working with PHP and WordPress. I tried exploring how to escape and sanitize, and I got a little confused along the way.
I'd like to echo out the contents of an entire table from the database. I am unsure whether there is a better way of both creating a table in a more structured way, and I can't figure out how to escape the data when I don't select specific data from the database. Maybe i'm just confused. Any help or pointers is highly appreciated.
I found the code somewhere on Stack Overflow, edited a little and tried to understand it. I understand it now, but I am still confused on where to go from here.
<?php
$results = $wpdb->get_results( "SELECT * FROM user"); // Query to fetch data from database table and storing in $results
if(!empty($results)) // Checking if $results have some values or not
{
echo "<table width='100%' border='0' id='userTable'>"; // Adding <table> and <tbody> tag outside foreach loop so that it wont create again and again
echo "<tbody>";
echo "<tr>"; // Adding rows of table inside foreach loop
echo "<th>E-mail</th>" . "<th>Fornavn</th>" . "<th>Efternavn</th>" . "<th>Registreret den</th>";
echo "</tr>";
foreach($results as $row){ //putting the user_ip field value in variable to use it later in update query
echo "<td colspan='3'><hr size='2'></td>";
echo "<tr>";
echo "<td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "</td>" . "<td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td>"; //fetching data from user_ip field
}
echo "</tbody>";
echo "</table>";
}
?>
This part...
foreach($results as $row){
//putting the user_ip field value in variable to use it later in update query
echo "<td colspan='3'><hr size='2'></td>";
echo "<tr>";
echo "<td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "</td>"
. "<td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td>";
//fetching data from user_ip field
}
...would product html like
{3 columns}{content}{3 columns end}{row start}
{column start}{content}{column end} * 4
{3 columns}{row start}
{column start}{content}{column end} * 4
{3 columns}{row start}
{column start}{content}{column end} * 4
etc
What you want in your loop is probably:
{row start}{4 columns}{content}{4 columns end}{row end}
{row start}{column start}{content}{column end} * 4{row end}
which would look like this:
foreach($results as $row){
//putting the user_ip field value in variable to use it later in update query
echo "<tr><td colspan='4'><hr size='2'></td></tr>";
echo "<tr><td>" . esc_attr($row->email) . "</td>" . "<td>" . $row->firstname . "
</td><td>" . $row->lastname . "</td>" . "<td>" . $row->signuptime . "</td></tr>";
//fetching data from user_ip field
}
In your SQL-statement on your first row: SELECT * FROM user , all fields are returned into the $results array of objects. If you want to specify which fields are returned you simply include them instead of the *, e.g. SELECT id, email, firstname, lastname FROM user

How to put user input into a SQL Query

I have a database and I want the user to be able to have an input into what comes out. i.e
Select from Table where example = user input from box **(input by the user)**
Im guessing what I need is a variable to hold the value that then goes into the statement. I know how to get the value from the input box with script but can I use it like:
select * From handover WHERE hdate = variable. However I am guessing someone is going to talk to me about security if its even possible.
<html><body>
<input>User input</input> //That needs to go into statement
<?php
include 'config.php';
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = **user input**;");
echo "<table border='1'>
<tr>
<th>hdate</th>
<th>Delay</th>
<th>Health and Safety</th>
<th>Non Vsa</th>
<th>VSA</th>
<th>Dar</th>
<th>Other</th>
<th>Hour</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['hdate'] . "</td>";
echo "<td>" . $row['hdelay'] . "</td>";
echo "<td>" . $row['hs'] . "</td>";
echo "<td>" . $row['nv'] . "</td>";
echo "<td>" . $row['vsa'] . "</td>";
echo "<td>" . $row['dar'] . "</td>";
echo "<td>" . $row['other'] . "</td>";
echo "<td>" . $row['hour'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Any help is welcome and advice on the best language to use for this.
Kind Regards
Fintan
first of all, this question has nothing to do with javascript & ajax. so you can delete those tags.
you want to show/search data from mysql.
$result = mysqli_query($con,"SELECT * FROM handover WHERE hdate = '".$_POST['abc']."' ");
this is when you want to check if hdate column have exact data as user input ( $_POST['abc'] ).
and also don't forget to use mysqli_real_escape_string
you can learn common mysql pattern queries from here: http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html

How to put a break in the output when specific values change using mysqli php

I am building a website to list statistics for bowling tournaments over the last 24 years. Using the following code generates a long, single table showing all the data. I would like to put a break in the table when the $row['season'] value changes, i.e., from 1990-1991 to 1991-1992, and for each subsequent change of seasons and echo either an html horizontal line between seasons or put the value of the season from the database, i.e., 2013-2014 at the top of each table segment. After a week of searching the web haven't figured out an answer. Here's the code I have now. Needs to be mysqli.
$result = mysqli_query($conn,"SELECT * FROM members INNER JOIN scores ON members.id=scores.memberID WHERE format LIKE '%s%' ORDER BY year, STR_TO_DATE( month, '%b' ), format ASC;");
echo "<table border='0'>
<tr>
<th>Name</th>
<th>Hometown</th>
<th>Month</th>
<th>Year</th>
<th>Season</th>
<th>Center</th>
<th>Center City</th>
<th>Format</th>
</tr>";
foreach($result as $row) {
echo "<tr>";
echo "<td>" . $row['firstName'] . " ". $row['lastName'] . "</td>";
echo "<td>" . $row['hometown'] . "</td>";
echo "<td>" . $row['month'] . "</td>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['season'] . "</td>";
echo "<td>" . $row['center'] . "</td>";
echo "<td>" . $row['centerCity'] . "</td>";
echo "<td>" . $row['format'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
The answer is actually already given but it looks like your new with php so here is a smal example i hope its useful to you.
You need to insert some if statements to check if there is any change of year. same goes for any other checks you want to perform.
this is something you could do...
<?php
$lastYear = null;//you can also set the first year manually of course
foreach($result as $row) {
//set the first year
if($lastYear == null){$lastYear = $row['year'];}
//check if the year changed or not
if($lastYear == $row['year']){
//if the year didnt change... do something
}else{
//your year changed... do something different
$lastYear = $row['year']; //update your 'last'year
}
}
?>
I hope this will help you.

How can I access query results in php where I'm returning values AS things? (Rather than looking at fields)

Apologies, I can't think of how to phrase this better (which has the additional problem of making it more difficult to research an answer, too). Suggestions for editing terms for clarity are more than welcome.
I am running two queries on a table in my database. The first simply returns all results within certain constraints imposed by the user - I'm echoing this out to a table with no problems at all. The second returns a COUNT and a SUM AS things, which I am having trouble accessing and echoing to the screen.
First Query -
$results = $connection->query(" SELECT `Date`, `Test`, `Errors` ... ");
while($result = $results->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $result['Date'] . "</td>";
echo "<td>" . $result['Test'] . "</td>";
echo "<td>" . $result['Errors'] . "</td>";
echo "</tr>";
}
This works perfectly well. As expected, it echos out a table with the results in each row.
Second Query -
$totals = $connection-query("SELECT COUNT(*) AS Tests, SUM(`Errors`) AS TotalErrors ... ");
echo "<th>Total Tests</th>";
echo "<td>" . $totals['Tests'] . "</td>";
echo "<th>Total Errors</th>";
echo "<td>" . $totals['TotalErrors'] . "</td>";
I cannot seem to access the values in the second query to echo them to the screen.
I have tried using var_dump to ensure the query is returning results correctly, and it is. If I use var_dump($totals->fetch_assoc()); it will display array(2) { ["Tests"]=> string(2) "33" ["TotalErrors"]=> string(1) "9" }, as expected.
I'm not sure where I'm going wrong, looking at my syntax, it seems the same as when I access the values from the first query, but I'm not sure if it should be different because I am returning values AS rather than looking at field names.
Try
$results = $connection->query("SELECT COUNT(*) AS Tests, SUM(`Errors`) AS TotalErrors ... ");
$totals = $results->fetch_assoc();
echo "<th>Total Tests</th>;
echo "<td>" . $totals['Tests'] . "</td>";
echo "<th>Total Errors</th>";
echo "<td>" . $totals['TotalErrors'] . "</td>";

Categories