Using PHP variable in mysql_query string - php

OK guys. I have a somewhat complicated issue with passing PHP variables into the mysql_query string.
The $_GET['date']; when passed will contain something like: 2015_01_07_1
I need to have the GET data passed into the table names using the $week variables.
<?php
$week= $_GET['date'];
$con=mysqli_connect("localhost","root","mypassword","beerhandpoker");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query
($con,
"SELECT games_brixx_gastonia_'$week'.rank, players_brixx_gastonia.name, games_brixx_gastonia_'$week'.points
FROM games_brixx_gastonia_'$week', players_brixx_gastonia
WHERE games_brixx_gastonia_'$week'.email = players.email
ORDER BY games_brixx_gastonia_'$week'.rank
LIMIT 20"
);
echo "<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['rank'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Change the string literal to:
"SELECT games_brixx_gastonia_$week.rank,
players_brixx_gastonia.name,games_brixx_gastonia_$week.points
FROM games_brixx_gastonia_$week, players_brixx_gastonia
WHERE games_brixx_gastonia_$week.email = players_brixx_gastonia.email
ORDER BY games_brixx_gastonia_$week.rank
LIMIT 20"
You have to remove the ' characters;
It's going to the db as games_brixx_gastonia_'2015_01_07_1'.rank

Why do you put single quotes? It should work:
SELECT games_brixx_gastonia_{$week}.rank, players_brixx_gastonia.name, games_brixx_gastonia_{$week}.points
FROM games_brixx_gastonia_{$week}, players_brixx_gastonia
WHERE games_brixx_gastonia_{$week}.email = players.email
ORDER BY games_brixx_gastonia_{$week}.rank
LIMIT 20
Anyway, I'd rather advice you to use statement instead. Check it out:
http://php.net/manual/pt_BR/mysqli.prepare.php

Just remove the ' characters. Otherwise the query would try to get data from the table games_brixx_gastonia_'2015_01_07_1' and not games_brixx_gastonia_2015_01_07_1.

Related

Why is data is not printed on webpage, after being fetched from mysql database?

$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
echo "Your food complain has been successfully fetched";
echo "<table border='1'>
<tr>
<th>Username</th>
<th>PNR Number</th>
<th>Food Complain Status</th>
</tr>";
while($row = mysqli_fetch_array($retval))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['pnrno'] . "</td>";
echo "<td>" . $row['complain_status'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "\r\n";
} else {
echo "Error: " . $retval . "<br>" . mysqli_error($conn);
}
Code inside the while loop is not getting executed(I think so), "Your food complain has been successfully fetched" this message is getting printed, table is formed, but username, pnrno, and complain_status after being fetched from database is not printed on webpage. Why is it so, please help.
Assuming the data exists, and you're sending the query the correct parameter, the likely culprit is how you're using your row variable. Since you're not telling mysqli to fetch the array in an associative manner, it's defaulting to an index.
You need to change your fetch function to:
mysqli_fetch_array($retval, MYSQLI_ASSOC)
$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
Your if is going to execute if the query successfully executes.
However, a query for a non-existent row will succeed, with zero rows.
You'll want to check the number of rows returned by the query, and show an error if there aren't any matching ones.

How to use PHP variables in MySQL queries with WHILE fetched rows?

I have successfully done the php script that connect to my database and return desired data. But i need to extend this script to insert a variable that will show the price with some calculations (tax,no-tax,margin etc.).
This script show me only price value of the first database row 0.00 in all fetched rows and its not correct - for the first database row is ok because product have 0.0000 price, but the other rows are filled with correct values. It seems like the while loop dont like my $styledprice variable . I can't figure how to show correct field values in all lines. Any ideas much apppreciated? I'm a PHP beginner!
$pricequery = "SELECT rrp FROM my_products";
$b2bprice = mysql_query($pricequery);
$rrps = mysql_fetch_array($b2bprice);
$price = $rrps['rrp'];
$styledprice = number_format($price, 2, '.', '');
$query = mysql_query("
SELECT
CONCAT(' <td> ',p.id,' </td><td> ',p.manufacturer,' </td><td> ',p.reference,' </td><td> ',p.name,' </td><td> ',p.quantity,' <td> ','".$styledprice."',' </td> ') AS row
FROM my_products p
");
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while($row=mysql_fetch_array($query))
{
echo "<tr>".$row['row']."</tr>";
}
echo "
</table>";
Yes i know about mysql_ functions that are deprecated.
Something like this should work better.
It seperates the resultset from the database and the output via HTML.
// Get the Result Set
$result = mysql_query("SELECT p.id, p.manufacturer, p.reference, p.name, p.quantity FROM my_products p");
// Convert the rows and columns from the Result Set to a PHP Array
$data = array(); // empty array
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
// Now you have access any row or column
echo "<table>";
foreach($data as $row){
// prepare the data
$formatttedQuantity = number_format($row['quantity'], 2, '.', '');
// show each Table Row
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['reference'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $formatttedQuantity . "</td>";
echo "</tr>";
}
echo "</table>";
It looks like you can do this all in one sql command like:
<?php
$sql = "SELECT * FROM my_products";
$result = mysql_query( $sql );
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while( $row=mysql_fetch_array( $result ) ){
$price=$row['rrp'];
$styledprice = number_format( $price, 2, '.', '' );
echo "
<tr>
<td>{$row['id']}</td>
<td>{$row['manufacturer']}</td>
<td>{$row['reference']}</td>
<td>{$row['name']}</td>
<td>{$row['quantity']}</td>
<td>{$styledprice}</td>
</tr>";
}
echo "
</table>";
?>

Can't reference MySQL by column names

I'm struggling to reference the MySQL data simultaneously by both column name and individual row number.
The code sample below does the following;
Successfully
prints the correct data to a table when looping through the whole table, referencing columns by name OR number.
when referencing individual rows in the database the correct columns by the column number
But I can't get it to successfully reference individual rows (by number) and columns (by name) at the same time.
Apologies if this is a ridiculous question, I'm new to PHP and MySQL.
I think my description is abysmal, so maybe this will help. Of the four options available (column either by name or number, and rows either individually or looping through a group) it works like this;
Column by number, each row in a loop. Yes.
Column by name, each row in a loop. Yes.
Column by number, individual row. Yes.
Column by name, individual row. NO! (as shown in the last line of code, a is a column in my database)
Does anyone please have any advice on what I'm doing wrong?
Code:
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<t
h>Lastname</th>
<th>test</th>
<th>order</th>
</tr>";
$ind = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . ($row['age'] * 1) . "</td>";
echo "<td>" . ($row['a']) . "</td>";
echo "<td>" . $ind. "</td>";
echo "</tr>";
$ind += 1;
}
echo "</table>";
$sql="SELECT * FROM Persons ORDER BY PID";
if ($result=mysqli_query($con,$sql))
{
// Prints single entry AP
print "<br>";
$rowNumber = $id;
mysqli_data_seek($result, $rowNumber);//start row is whatever you need to be the first row
$row = mysqli_fetch_row($result);
print "<br>";
//-----------------------------------------------------
$mathString = $row[1];
$description = $row[4];
echo "math string:" . $mathString . "<br>";
echo "a is said to equal:" . $description . " - " . $row['a'];

Trying to pass a student key from a html form to a php file to scan a database

Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

How to make this code to loop 10 times per page?

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbsql", $con);
$result = mysql_query("SELECT * FROM testimonial where approved='Yes'");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Review</th>
<th>Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['full_name'] . "</td>";
echo "<td>" . $row['review'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
If you are looking for that specific block of data to loop 10 times every time the page is loaded simply use a for() loop
for($i=0;$i<10;$i++)
{
// block of data
}
But I assume that that is not what you are asking since it would be impractical (as far as I can see).
To print 10 results, add
limit 10
to the end of your query. If you're using pagination, however, you will need to start the limit somewhere (e.g. limit STARTING_NUMBER, NUM_OF_RESULTS)
Good luck!
Dennis M.
replace
SELECT * FROM testimonial where approved='Yes'
with
$offset = 0; //calculate your offset here as per page;
SELECT * FROM testimonial where approved='Yes' limit $offset, 10

Categories