Can't reference MySQL by column names - php

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'];

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.

Read More Button

I have the below table in my site...
and what I want is that when i click on the read more link to redirect me to the page view_announcement.php and in this page to display me the whole data for this specific row.
For example, if we click on the link in the second row I want in the view_announcement.php to load all the data for this specific row.
My code in order to display this table is this...
<?php
$q = ($_GET['q']);
$con = mysqli_connect('localhost','root','smogi','project');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"project");
$sql="SELECT author,category,subject,content FROM announcements WHERE category = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Author</th>
<th>Category</th>
<th>Subject</th>
<th>Content</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . 'Read More' . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The view_announcement.php file doesn't contain any code yet because i dont know what to write.
One way to do it is to append a query variable to the "Read More" links. You'll probably need a unique identifier, such as an ID number, on your announements table. If you don't have one yet, I suggest adding one and setting it up to auto-increment.
You would want to modify your query to include the unique ID number:
$sql="SELECT id,author,category,subject,content FROM announcements WHERE category = '".$q."'";
Then you would modify the loop which prints your table out to include those unique IDs in the URL to view_announcement.php
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['author'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . 'Read More' . "</td>";
echo "</tr>";
}
And in your file view_announcement.php, you would make another SQL query to get the full data for a specific row, like this:
$sql="SELECT * FROM announcements WHERE ID = '".$_GET['id']."'";
If you click any button, that redirects to view_announcement.php file, where you can get the subject values.
Use that subject values in your query to get all the details which relates to that subject.

Can you store selected sql query values in the url and then retrive them with $_GET?

I'm trying to make it so that when a users clicks one of the rows,it will take them to a new page whose link is given as the value of the row they selected and then retrieve the value with $_GET["timesub"].
Anyone know how to do this?
mysql_select_db("RRRC", $con);
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum=$loc");
echo "<table border='1'>
<tr>
<th> Submitted </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";
Assuming that $row['timesub'] identifies a row in your data set (I doubt it), just fix your echo instruction as:
echo "<td>" . $row['timesub'] . "</td>";
Escaping the html quotes properly.
echo "<td><a href='roomdata.php?timestamp=".$row['timesub']."'>".$row['timesub']."</a></td>";
Close the outer " before the . concatenator, replace the inner " with '
A good practice is to use the row's primary key to reference your get query; but yes - this can be done.
All you have to do is store the get data into a sanitized variable, and perform the required SQL lookup / data display.
EX:
$roomnum=mysql_real_escape_string(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['roomnum']));
Now, given that "roomnum" is your primary key just look it up and display:
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum='$roomnum'");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";

Store and display MySQL result to/from PHP array

Suppose I have the following MySQL table result:
ID price
-------------
1 10
2 20
3 30
Basically what I want to accomplish is to store these values to a PHP array, and have these values displayed/echoed as a HTML table on a per row basis.
I could do something like:
if($result) {
$i = 0;
while ($row = mysql_fetch_array($result)) {
$id[$i] = $row['id'];
$price[$i] = $row['price'];
}
}
And just have those elements echo together with the HTML table.
However, I also need to have a function that allows the user to delete a row. With that mind I believe I need to have some sort of a 'key' for every row as the identifier for deletion -- a feature which multidimensional array supports.
There's nothing preventing you from using a multi dimensional array and using one of the unique values as an index:
// Store result
$data = array();
if($result) {
while ($row = mysql_fetch_array($result)) {
$data[$row['raiser_id']] = $row;
}
}
// Building table
echo "<table>";
foreach ($data as $row)
{
echo "<tr>";
echo "<td>" . $row['raiser_id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fcr'] . "</td>";
echo "<td>" . $row['date_of_application'] . "</td>";
echo "<td>" . $row['no_of_heads'] . "</td>";
echo "<td>" . $row['place_of_farm'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Removing an entry by raiser_id
$raiser_id = 10;
if (!empty($data[$raiser_id]))
{
unset($data[$raiser_id]);
echo "Removed entry";
}
else
{
echo "No entry to remove";
}
To delete a row from the database, you have to have another PHP script and have to call it using POST method and run an SQL query in it.
If you are talking of just displaying this table, PHP has nothing to do here then - go for JavaScript.
By the time a user sees his table, there is no mysql result, no PHP array and no whole PHP running either. It's all dead long time ago. Keep that in mind.

Create an HTML5 range "slider" that does the same as the following drop down menu

I have a drop down menu, which is filled from a database. When I select a value in the menu it displays a table of the data selected from the database. I'd like to change this to an HTML5 range slider. So far with no luck. I also want to show the values (dates) beside the range as I move along it.
This is the code to the drop down menu:
// Set SQL string
$query = "SELECT * FROM Test";
// Execute SQL
$result = mysql_query($query);
// Find number of rows in the resulting recordset array
$num = mysql_numrows($result);
// Initialise loop counter
$i = 0;
echo ("<form><select name='users' onchange='showUser(this.value)'>");
// Loop through recordset until end
while ($i < $num) {
// Associate variables for result at position i at table location specified
$Time = mysql_result($result, $i, "Time");
// Echo each entry as an OPTION for the Select List
echo ("<option value=\"$Time\">$Time</option>");
// Increment Loop Counter
$i++;
}
echo ("</select></form><br>");
gettime.php:
$sql = "SELECT * FROM Test WHERE Time = '" . $q . "'";
$resultb = mysql_query($sql);
if (!$resultb) {
echo "<p>The following SQL failed</p><p>" . $sql . "</p>";
}
echo "<table border='1'>
<tr>
<th>Time</th><th>First PC Room</th>
<th>First Group Study Room 1</th>
<th>First Group Study Room 2</th>
<th>First Main Room</th>
</tr>";
while ($rowb = mysql_fetch_array($resultb)) {
$bmsTime = $rowb['Time'];
//Convert Excel Timestamp of DB to Unix Timestamp
$unixtime=($bmsTime-25569)*86400;
$readable=date('l jS \of F Y h:i:s A',($unixtime));
echo "<tr>";
echo "<td>" . $readable . "</td>";
echo "<td>" . $rowb['firstPCroom'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm1'] . "</td>";
echo "<td>" . $rowb['firstGrpStdyRm2'] . "</td>";
echo "<td>" . $rowb['firstmainroom'] . "</td>";
echo "</tr>";
}
echo "</table>";
Below is what I have so far on the "slider":
echo "<input id='slider' type='range' min='0' max=\"$num\" step='any' />
<span id='range'> </span>";
?>
<script>
var selectmenu=document.getElementById("slider");
var colorchange;
selectmenu.onchange=function changecolour(){
if (selectmenu.value<"0.5")
{colorchange=0}
else if (selectmenu.value>="0.5") {colorchange=Math.round(selectmenu.value)}
document.getElementById("range").innerHTML=colorchange;
}
</script>
Any help would be greatly appreciated! Thanks
Here is a jsFiddle that updates a table row using jQuery. Presumably you would replace the data with an AJAX call.
If you were a little more specific about where exactly you were having trouble, someone else may be able to tailor a solution that better fits your needs.

Categories