I'm working on a frequently asked questions, but for administration I want to be able to see the current frequently asked questions that have been stored in the database, and below that a form to post a new question & answer, which upon submitting will refresh the page with the new question and answer.
Here's the thing:
I've gotten it to post just fine, but I can only display the most recent one...
here's my code so far:
Getting:
<?php
//select database table
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
//Request Values
while ($row = mysql_fetch_array($queryresult)){
$faqQuestion = $row['question'];
$faqAnswer = $row['answer'];
}
//echo variables
echo "<p>$faqQuestion</p>" . "<p>$faqAnswer</p>" . "<br />";
//if question and answer have null values
if ((empty($faqQuestion))&&(empty($faqAnswer))){
echo("<div><p>No Questions available</p></div>");
}
?>
<?php
mysql_free_result($queryresult);
mysql_close($conn);
?>
Posting:
<?php
include("database_conn_dcs.php");
if($_POST){
$question = ($_POST['question'])? $_POST['question']:null;
$answer = ($_POST['answer'])? $_POST['answer']:null;
$sql="INSERT INTO faq (talen_idtalen, question, answer)
VALUES ('$idtalen', '$question', '$answer')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
header("location: faq_admin.php");
}
?>
My other issue is that it also posts blank stuff. how do i prevent PHP sending null values to the database (it's already stated the variables are non-null?
Thank you so much in advance!!!
First, your echo should be in the while loop, otherwise each time it loops, your two variables are being overwritten.
Secondly, you only want to display no questions available if no results were returned, which is checked by the mysql_num_rows.
Thirdly, your input code is vulnerable to SQL Injection, which could get your website compromised. To prevent this, use prepared statements, and bind your user input ($_POST variables) instead of including them directly in the query.
<?php
//select database table
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
//Request Values
while ($row = mysql_fetch_array($queryresult)){
$faqQuestion = $row['question'];
$faqAnswer = $row['answer'];
//echo variables
echo "<p>$faqQuestion</p>" . "<p>$faqAnswer</p>" . "<br />";
}
if(mysql_num_rows($queryresult) <= 0) {
echo("<div><p>No Questions available</p></div>");
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Related
Noob alert here. I'm just (trying to) teaching myself PHP because I need it on my internship job. Now I am creating a survey and I am trying to use while loops to show the questions and their respective answers onto my XAMPP. I am using this code:
<?php
mysqli_select_db($conn, "surveyordina");
//code hier schrijven
$sql = "SELECT questions_body FROM survey_questions where subthema_id = 1";
$sql2 = "SELECT answer_body FROM survey_answers where answer_id = 1 or answer_id = 2 or answer_id = 3";
$result = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn, $sql2);
if(mysqli_num_rows($result2) > 0){
while($row = mysqli_fetch_assoc($result)) {
echo "<br>" ."Vraag: <br>" . $row["questions_body"]. "<br>";
while($row_answer = mysqli_fetch_assoc($result2)) {
echo $row_answer["answer_body"]. "<br>";
}
}
}
else{
echo "No results";
}
Now the returning part of this code looks like this:
Vraag:
Is the organization aware of where all the personal data is stored? Be it on-site or in the cloud, hosted by the company or by a third party?
Yes
No
I don't know
Vraag:
Is the organization able to locate and find personal data of a particular data subject?
Vraag:
Does the organization have technology in place to return all personal data on a given data subject, given a single search from personnel?
Vraag:
testerino kekkerino
I am trying to get the Yes, No, and I don't know parts under each and every question but only seem to get it under one of the questions.
Is there a method to return the whole answer part under each question? If so, am I on the right path or am I doing something completely wrong?
Thanks in advance.
Once you hit the end of a result-set, mysqli_fetch_assoc() doesn't just keep cycling through. So you're hitting the end of the $result2 set within the first outer loop, and then that's it, there are no more results to fetch.
You should fetch all of the $result2 results outside of the $result loop, assign the results to a variable, and then loop through that array within the $result loop.
Something like:
if(mysqli_num_rows($result2) > 0){
$result2Set = mysqli_fetch_all($result2, MYSQLI_ASSOC);
while($row = mysqli_fetch_assoc($result)) {
echo "<br>" ."Vraag: <br>" . $row["questions_body"]. "<br>";
foreach($result2Set as $row_answer) {
echo $row_answer["answer_body"]. "<br>";
}
}
}
I'm a student studying web programming im trying to display some of information from my db table which are(name, date, dll), all of the information are displayed perfectly except my id number from the db table and also there are no error so its hard for me to detect what i did wrong. can anyone see what i did wrong in my coding and explain what have i missed?
for further reference this is my php coding:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("tempahperalatan");
if(isset($_POST['hantar']))
{
$noID = 'noID';
$pemohon = $_POST['pemohon'];
$trkhMula = $_POST['trkhMula'];
$trkhAkhir = $_POST['trkhAkhir'];
$n_program = $_POST['n_program'];
$lokasi = $_POST['lokasi'];
$n_anjuran = $_POST['n_anjuran'];
$catatan = $_POST['catatan'];
$masa = $_POST['masa'];
$t_Log = $_POST['t_Log'];
$modified_date;
$modified_time;
$sql = "INSERT INTO daftartempah (pemohon, trkhMula, trkhAkhir, n_program, lokasi, n_anjuran, catatan, modified_date, modified_time) VALUES ('$pemohon', '$trkhMula', '$trkhAkhir', '$n_program', '$lokasi', '$n_anjuran', '$catatan', CURDATE(), CURTIME())";
$res = mysql_query($sql);
}
$viewPerson = "SELECT * FROM daftartempah";
$viewPersonRes = mysql_query($viewPerson);
?>
and this is a table im trying to display some of my info from my db table:
<?php
while($row = mysql_fetch_array($viewPersonRes)){
echo "<tr>";
echo "<td".$row['noID']."</td>";
echo "<td>".$row['trkhMula']."</td>";
echo "<td>".$row['modified_time']."</td>";
echo "<td>".$row['n_program']."</td>";
echo "<td>".$row['pemohon']."</td>";
echo "<td>".$row['n_anjuran']."</td>";
echo "<td>".$row['lokasi']."</td>";
echo "<td>".$row['catatan']."</td>";
echo "</tr>";
}
?>
my table name from my db is: daftartempah
thank you in advance, your help is much needed :)
You have a missing closure for your <td> tag.
echo "<td".$row['noID']."</td>";
^ right there.
That's why it's not displaying.
Therefore:
echo "<td>".$row['noID']."</td>";
and looking at your developer console and the HTML source would have shown you something about it.
Make sure that you also have the opening and closing <table> - </table> tags. That's unknown.
You're also practicing with an outdated API, which isn't good practice to begin with.
Use either the mysqli_ or PDO API for "this century".
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
You're also open to an serious SQL injection; use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";
Hi I am trying to fetch data from a particular coloumn from all rows.
Eg Situation:
DB Data: id, fbid, name
$sql = 'SELECT id FROM table WHERE table.fbid IN (1234,5678,4321)';
$sql_run = mysql_query($sql);
$sql_fetch = mysql_fetch_assoc($sql_run);
print_r($sql_fetch);
This returns the data when I test it using Sequel PRO or PHPmyAdmin.
But when I print the array it only displays one value.
Can you help me with a solution or tell me where I'm going wrong?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Before using a function, or - at least - when it does not what you expect - it's always a good idea to read the function description in the manual page.
PHP provides extremely easy access to its manual pages. All you need to type in the address bar is php.net/function name. It takes less time than typing whole question on Stack Overflow, yet you will get exactly the same answer. Think of efficiency.
You need to loop through each row
$sql_run = mysql_query($sql) or die(mysql_error());
while ($sql_fetch = mysql_fetch_assoc($sql_run)) {
print_r($sql_fetch);
}
I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.