What I am trying to do is add information from extracted with php into a css tooltip. The text, instead of appearing inside the tooltip, appears next to the label tag I have. The tooltip appears over the label tag. Here my code so you can probably help me:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<?php
//Connect to the database
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query = "SELECT * FROM programmer";
$resultset = $conn->query($query);
function projects($prog_id){
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query2= "SELECT * FROM programmer pm INNER JOIN project p ON pm.programmer_id=p.programmer_id WHERE pm.programmer_id=:id";
$resultset2= $conn->prepare($query2);
$resultset2->bindValue(":id",$prog_id);
$resultset2->execute();
$isthere=false;
while($row2 = $resultset2->fetch()){
echo "Working on project ".$row2['project_id'].".";
$isthere=true;
}
if(!$isthere){
echo "No projects";
}
}
while ($row = $resultset->fetch())
{
echo "<p class='col'>";
echo "<input type='checkbox' name='programmers[]' id='programmer".$row['programmer_id']."' value='".$row['programmer_id']."'>";
echo "<a href='' class='help tip-below' data-tip='".projects($row['programmer_id'])."'><label for='programmer".$row['programmer_id']."'>".$row['programmer_name']." ".$row['programmer_surname']."</label></a>";
echo "</p>";
}
?>
Thanks a lot for helping me out!
Your function projects() has no return value (instead you print it, which is bad practice btw)!
Change
while($row2 = $resultset2->fetch()){
echo "Working on project ".$row2['project_id'].".";
$isthere=true;
}
if(!$isthere){
echo "No projects";
}
To something like this
$result = "";
while($row2 = $resultset2->fetch()){
$result .= "Working on project ".$row2['project_id'].".";
}
if(empty($result)){
return "No projects";
}
return $result;
To clarify this, you can think of a function as a calculator maybe. You input specific data (an equation e.g.) and it returns something (the solution). What happens inside, you don't know and don't really care.
Now back to PHP, the input is clear: the parameters ($prog_id), but your function has no return, instead it just prints something to the screen (what you really shouldn't do outside a development environment). To test this you can use
var_dump( projects($some_id) );
And it will return NULL (because no return was specified), but what you really wanted was a string of some sort.
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.
Source can be found here: results.php
and the zip: Results zip
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo '<p><strong>You have not entered search details. Please go back and try again.</strong></p>';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
# $db = new mysqli("*","*","*","*");
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from acronymns where ".$searchtype." like '%".$searchterm."%' ORDER BY title ";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of records found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". ";
echo $row['acro'];
echo " - ";
echo $row['title'];
echo "</strong><br />";
echo $row['desc'];
echo "</p>";
}
// $result->free();
$db->close();
Output looks like:
Americans with Disabilities Act (ADA)
The Americans with Disabilities Act was enacted in 1990 to establish the prohibition of discrimination on the basis of disability, which may include autism. The ADA is divided into three Titles. Title I speaks to employment law, Title II covers State and Local activities (including public transportation), and Title III relates to accommodations in public buildings and businesses.
The link is: www.ada.com target="_blank" Americans with Disabilities Act</a> (within the MySql db.
The actual link shows: http://mysiteishere.com/"www.ada.com" which of course makes a 404 Error.
Thanks ahead of time.
Just because the desc filed contains URL's doesn't mean they will autmoatically show up as links in your HTML. You need to output the links as an href value in an <a> element to make a clickable link. You are probably best off not storing full HTML in your DB, but rather just the link. It looks like you combination now is producing an invalid link. Simple look at your HTML source and fix it.
From what you said, it seems that you're not including the link correctly. It doesn't have anything to do with the $row['desc'] but what's inside it. When you're inserting the link from whatever form you're using, use the following.
ex:
Americans with Disabilities
You can use the below function while fetching 'DESC' column
function make_links_clickable($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i', '$1', $text);}
For Eg.
$text = 'Here is link: http://google.com And http://example.com inside. And another one at the very end: http://test.net';
echo make_links_clickable($text);
Went ahead and changed my code and the text in the db. In the db I removed the Text.. and put the in between parentheses. The Php I changed to the following and now it shows the links with the urls, so it works. It's the "a href.." that I can't make work. I don't understand why though.
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<strong>".($i+1).". ";
//echo $row['acro'];
//echo " - <br />";
//echo "<br>";
echo $row['title'];
echo " - ";
echo "<br>";
echo "</strong>";
$text = $row['desc'];
$text = preg_replace('/(^|[^"])(((f|ht){1}tp:\/\/)[-a-zA-Z0-9#:%_\+.~#?&\/\/=]+)/i','\\1\\2', $text);
echo $text;
}
The link in the MysqlDB should be:
Americans with Disabilities Act
Now lets assume you got this right, you should look at your charset of your DB, just making sure they match your editors charset.
That said, please post the output of HTML "Show source".
The question might seem a little odd but I will show you what I mean :)
So I have made a webpage that contains comments that have been made by authorised users (teachers). That is another piece of code in another page so that works perfectly.
Of course it should be possible for the person who made the comment to change his own comments in case of mistakes etc.
I managed to show the user his own comments with his comments in seperate text areas.
The text areas have no specific name and are just called txtComment, how do I make them unique for every comment (which is flexible because comments can be added later).
I think that is the issue why I cannot update the changed/adapted textareas after I press the button.
I hope you guys understand what I am trying to say :p
I changed Dutch words mostly to English so if there is a spelling error that is due to that :)
This is the code:
<?php
$sqlKlas = "Select * from tblcomments WHERE ForWho='".$_SESSION['User']."' AND ForWho='6HA1' OR VoorWie='6HA2'";
$resultKlas = mysql_query($sqlKlas) or die(mysql_error());
if (isset($_POST['btnAdaptCommentKlas'])){
while($rowKlas = mysql_fetch_array($resultKlas)){
$CommentNr = $rowKlas['CommentNr'];
$sqlUpdate = "Update tblcomments SET Comment='".$_POST['txtComment']."' WHERE CommentNr=$CommentNr";
$resultUpdate = mysql_query($sqlUpdate) or die(mysql_error());
echo "<tr>";
echo "<td>";
?><textarea name="txtComment" cols="80" rows="5"><?php echo $rowKlas['Comment']; ?></textarea><?php
echo "</td>";
echo "<td>".$rowKlas['ForWho']."</td>";
echo "<td>".$rowKlas['Datum']."</td>";
echo "</tr>";
}
}
else {
while($rowKlas = mysql_fetch_array($resultKlas)){
echo "<tr>";
echo "<td>";
?><textarea name="txtComment" cols="80" rows="5"><?php echo $rowKlas['Comment']; ?></textarea><?php
echo "</td>";
echo "<td>".$rowKlas['ForWho']."</td>";
echo "<td>".$rowKlas['Datum']."</td>";
echo "</tr>";
}
}
I would do it a little differently - updating separate to listing out the comments. Also You would have to set the textarea name containing the comment ID, like in my example:
<?php
$sqlKlas = "Select * from tblcomments WHERE ForWho='".$_SESSION['User']."' AND ForWho='6HA1' OR VoorWie='6HA2'";
$resultKlas = mysql_query($sqlKlas) or die(mysql_error());
if (isset($_POST['btnAdaptCommentKlas'])){
foreach($_POST['txtComment'] as $key => $value) {
$sqlUpdate = "UPDATE tblcomments SET Comment='".mysql_real_escape_string($value)."' WHERE CommentNr=".(int)$key;
$resultUpdate = mysql_query($sqlUpdate) or die(mysql_error());
}
}
while($rowKlas = mysql_fetch_array($resultKlas)){
$CommentNr = $rowKlas['CommentNr'];
echo "<tr>";
echo "<td>";
?><textarea name="txtComment[<?php echo $CommentNr; ?>]" cols="80" rows="5"><?php echo $rowKlas['Comment']; ?></textarea><?php
echo "</td>";
echo "<td>".$rowKlas['ForWho']."</td>";
echo "<td>".$rowKlas['Datum']."</td>";
echo "</tr>";
}
Also I would recommend not to use mysql_* function but use PDO or at least mysqli_* instead. Using mysql_real_escape_string() to escape the user input is highly recommended.
Also using MVC and separating the data manipulation (updating, fetching, creation) and data presentation (in an HTML template) would be much nicer and more maintainable for further development.
Instead of txtComment use txtComment[unique_id].
This way you can do something like
foreach(array_keys($_GET['txtComment']) as $id => $comment) { ...
then try this
$sqlUpdate = "Update tblcomments SET Comment='".$_POST['txtComment']."' WHERE OpmerkingNr='".$OpmerkingNr."' ";
and change this
$sqlKlas = "Select * from tblcomments WHERE ForWho='".$_SESSION['User']."' AND ForWho='6HA1' OR VoorWie='6HA2'";
to this
$sqlKlas = "Select * from tblcomments WHERE ForWho='".$_SESSION['User']."' AND (ForWho='6HA1' OR VoorWie='6HA2' )";
you could also check the user if logged in or not here
if (isset($_POST['btnAdaptCommentKlas'])){
try change it to
if (isset($_POST['btnAdaptCommentKlas']) AND $_SESSION['User'] !=0 ){
obs: I advice you to use PDO instead.
Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)