I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.
Related
I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.
I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].
I currently have this code which displays all required information on the page:
$sql = "select * from livecalls ORDER BY Completion_Date ";
$query = mysql_query( $sql );
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td>$row[ID]</td>";
echo "<td>$row[Type]</td>";
echo "<td>$row[VNC_Number]</td>";
echo "<td>$row[Completion_Date]</td>";
echo "<td>$row[Logged_By]</td></tr>";
}
echo "</table>";
This works fine, however I am wanting to be able to click the $row[ID] section to open a new window and display the $row[Problem] which is related to that ID number..
I'm struggling to think how to get the ID information across to a new page to be able to search for the right Problem information to display and the code to do this?
Any help would be appreciated.
You can use a anchor tag for this purpose like
echo "<tr><td><a href='yourpage.php?id=".$row[ID]."'>".$row[ID]."</a></td>";
and in new page, you can use
$_GET['id'] for getting the id.
Also while echoing html along with php variable try to do like this:
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td><a href='yourpage.php'>".$row['ID']."</a></td>";
echo "<td>".$row['Type']."</td>";
echo "<td>".$row['VNC_Number']."</td>";
echo "<td>".$row['Completion_Date']."</td>";
echo "<td>".$row['Logged_By']."</td></tr>";
}
I guess your not using any php framework (ex. codeigniter). Because if you do,this is easy using routing.
The very basic solution is Passing variables in a URL
http://html.net/tutorials/php/lesson10.php
Then if you want it to open in a new window instead of current window use
Use _blank in your a href
Visit W3Schools!
$sql = "select * from livecalls ORDER BY Completion_Date ";
$query = mysql_query( $sql );
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td><a href='your_url/?id=".$row[ID]."'>$row[ID]</a>`enter code here`</td>";
echo "<td>$row[Type]</td>";
..
...
....
When I click on any link it opens all movies in my database. I want only that movie which begins with that letter and I don't know where I've made a mistake. Here is my code:
$azRange = range('A', 'Z');
foreach ($azRange as $letter){
echo ''.$letter.' | ';
}
if(isset($_GET["task"]) && $_GET["task"] == "view"){
$naslov = $_GET['naslov'];
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
$result = mysql_query($query)
or die ('SQL Greska: '.mysql_error());
if($result){
while($filmovi = mysql_fetch_array($result)){
echo '<center><b>';
echo '<td><img src="img/'.$filmovi["slika"].'" border="0" width="100" /></td>';
echo '</br>';
echo '<td>'.$filmovi["naslov"].'</td>';
echo '<td> ('.$filmovi["godina"].')</td>';
echo '<br>';
echo '<td>Trajanje: '.$filmovi["trajanje"].' min</td>';
echo '</b></center>';
echo '</tr>';
}
You are not passing the letter to the database query at any point.
$query =
"SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE naslov LIKE '$naslov%'
ORDER BY naslov";
Your query
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
is fetching all the movies from the database. There is no filtering here. Add some where conditions to this query and you'll get the expected result.
Changing to this query might help:
SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE `naslov` LIKE '{$naslov}%'
ORDER BY naslov
Since others have already answered your question (missing WHERE clause), I just want to mention that the <center> HTML tag is deprecated, and you should use CSS instead.
The mysql driver for PHP is also outdated, so instead of using:
mysql_query($query);
you should use
mysqli_query($link, $query);
for better security, OOP support, prepared statements, and transactions.
You can read about it here
Even if you are a beginner and you don't care about what those features mean, you should try and get into the habit of using mysqli anyway, so that when the day comes that you learn to appreciate it, you don't have to go back and update all of your code.
I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit