In a php session - php

}
put returns between paragraphs
for linebreak add 2 spaces at end
italic or bold
indent code by 4 spaces
backtick escapes like _so_
quote by placing > at start of line
to make links (use https whenever possible)

You could have another session that stores the answers as an array, and add to it after each successful post
Something like this could work:
<?php
$totalQuestions = count($ques);
$_SESSION['answers'] = $_SESSION['answers'] ?? [];
// Get current question, default to 1
$currentQuestion = count($_SESSION['answers']) == $totalQuestions ?
$totalQuestions :
$_SESSION['answers'] + 1;
?>
<div class='questionHeader'>
<label>Question <?php echo $currentQuestion ?> of <?php echo $totalQuestions ?></label>
</div>
<br>
<div class='question'>
<?php echo $ques[$currentQuestion-1] ?>
</div>
Answer: <input type='text' id='answerOneSub' name='answerOneSub'>
<button type='submit' value='submit' name='submit'>Submit!</button>
<?php
if (isset($_POST['submit'])) {
$_SESSION['answers'][] = $_POST['answerOneSub'];
echo "<br>" . $_SESSION['answerOneSub'];
}
?>

You can use query param like this:
<?php
$page = 1;
if (isset($_GET["page"])) {
$page = (int)$_GET["page"];
}
$url = strtok($_SERVER["REQUEST_URI"], '?');
echo "<form method='post' action='" . $url . "?page=" . ($page + 1) . "'>";
echo "<div class='questionHeader'><label>Question [$page] of 6</label></div>";
echo "<br>";
echo "<div class='question'>" . $ques[$page - 1] . "</div>";
echo "<br>";
echo "Answer: ";
echo "<input type='text' id='answerOneSub' name='answerOneSub'>";
echo "<button type='submit' value='submit' name='submit'>Submit!</button>";
echo "</form>";
if (isset($_POST['submit'])) {
$_SESSION['answerOneSub'] = $_POST['answerOneSub'];
echo "<br>" . $_SESSION['answerOneSub'];
}

Related

MySQL returned an empty result set when inserting multiple rows

enter image description hereI am new to PHP and Mysql. i am trying to create a quiz project where multiple questions in a quiz will be inserted into the database once. How can i go about it. I have searched for solutions here and i tried using foreach. i am not having errors but it is not uploading
here is my form
<form class="quiz-questions">
<h1>Title Of Quiz</h1>
<?php
for($counter = 1; $counter <= $_SESSION['quiz_no']; $counter++)
{
echo "<div class='quiz-left'>";
echo "<div>";
echo "<label for='textarea' class='sn-quiz'>$counter</label><textarea name='question[]' class='textarea' id='example-three' placeholder='Enter the Question' cols='60' rows='3' ></textarea>";
echo "</div>";
echo "<div class='option-tag'>";
echo "<input type='checkbox' name='op1[]' value='optionA'>";
echo "<input type='text' name='optionA[]' placeholder='optionA'>";
echo "</div>";
echo "<div class='option-tag'>";
echo "<input type='checkbox' name='op1[]' value='optionB'>";
echo "<input type='text' name='optionB[]' placeholder='optionB'>";
echo "</div>";
echo "<div class='option-tag'>";
echo "<input type='checkbox' name='op1[]' value='optionC'>";
echo "<input type='text' name='optionC[]' placeholder='optionC'>";
echo "</div>";
echo "<div class='option-tag'>";
echo "<input type='checkbox' name='op1[]' value='optionD'>";
echo "<input type='text' name='optionD[]' placeholder='optionD'>";
echo "</div>";
echo "</div>";
}
?>
<input type="submit" name="insert_quiz" class="btn-primary btn btn-lg" placeholder="SUBMIT">
</form>
and here is my submit code
<?php
if(isset($_POST['insert_quiz'])) {
$quiz_add_id = $_SESSION['quiz_id'];
$count = $_SESSION['quiz_no'];
$i = 0;
foreach ($_POST as $val) {
$question = $_POST['question'][$i];
$optionA = $_POST['optionA'][$i];
$optionB = $_POST['optionB'][$i];
$optionC = $_POST['optionC'][$i];
$optionD = $_POST['optionD'][$i];
$op1 = $_POST['op1'][$i];
$query = "INSERT INTO quizzes (quiz_add_id, quiz_question, quiz_option_A, quiz_option_B, quiz_option_C, quiz_option_D, quiz_option_correct)";
$query .= "VALUES ('{$quiz_add_id}', '{$question}', '{$optionA}','{$optionB}','{$optionC}','{$optionD}', '{$op1}')";
$create_quiz_query = mysqli_query($connection,$query);
$i++;
}
if(!$create_quiz_query ){
die('QUERY FAILED' . mysqli_error($connection));
}
}
?>

Adding to a session array

<?php
session_start();
include("#nav.php");
include("dbconnectie.php");
echo "Plaatsingen: ";
$query = $db->prepare("SELECT * FROM shop");
$query->execute();
$result = $query->fetchALL(PDO::FETCH_ASSOC);
echo "<table>";
foreach($result as &$data) {
echo "<tr>";
$img = $data['img_url'];
echo "<td>" . $data["brand"] . "</td>";
echo "<td>" . $data["model"] . "</td>";
echo "<td> Condition: " . $data["cond"] . "/100 </td>";
echo "<td> Prijs: &dollar; " . number_format($data["price"],2,",",".") . "</td>";
echo "<td> <img src='$img' width='400' height='300' ></img> </td>";
echo "<td> Plaatsing nummer: " . $data['id_img'] . "</td>";
echo "</tr>";
echo "<br>";
}
echo "</table>";
if(isset($_POST['atc']))
{
if($_SESSION['on']){
$myarray = array('0');
$addtoarray = $_GET['id'];
array_push($myarray, $addtoarray);
$_SESSION['cart'] = $myarray;
echo "Toegevoogd aan uw winkelmandje.";
var_dump($_SESSION['cart']);
}else
{
echo "Log eerst in!";
}
}
?>
<html>
<title>Just for kicks</title>
<header>
</header>
<body>
<form method='post' action=''>
Plaatsing nummer invoeren:
<input type='number' name ='id' value ='id'><br>
<button type="submit" class="submit" name="atc" value="atc">Winkelmadje</button><br><br>
</form>
</body>
</html>
Between line 25 and 31 I'm trying to add numbers to the session array but I'm not sure how, because this is clearly not working. It doesn't add the number you fill in, at the form part. But it appears it doesn't do anything.
I trimmed your code down to just the bare minimum and added some inline comments. I made the assumption that the contents of $_SESSION['cart'] is an array.
Please notice:
POST was used consistently
The value of the input was removed (value ='id')
The check for $_SESSION['on'] was removed
Code
<?php
// Start your session.
session_start();
// The form was submitted.
if (isset($_POST['atc'])) {
// Get the cart so we can append to it.
// Assuming that the cart is an array.
$cart = (array)$_SESSION['cart'];
// Append the user's input to the end of the cart.
$cart[] = $_POST['id'];
// Store it in the session.
$_SESSION['cart'] = $cart;
// Dump out the session.
var_dump($_SESSION);
}
?>
<html>
<title>Just for kicks</title>
<header>
</header>
<body>
<form method='post'>
<label> Plaatsing nummer invoeren:
<input type='number' name='id'/>
</label><br>
<button type="submit" class="submit" name="atc" value="atc">Winkelmadje</button>
<br><br>
</form>
</body>
</html>

Tried to replace $_GET with $_POST, but now it won't display or update

I tried to retype a code of my groupmate, because the 'textarea' in here is going to be bombarded by a whole lot of string and the problem is that the request URI is too long. So I tried to change of all the $_GET to $_POST, because it won't be posted in the URL.
But the problem is that it won't display the input 'text' and 'textarea' in the isset. I don't know whether it's the isset that is the problem or the or the $_POST, but when I return it back to $_GET it works.
PHP Code for displaying the chapters to be updated and the update function.
<?php
if (isset($_POST['submit'])) {
$id = $_POST['cid'];
$title = $_POST['ctitle'];
$body = $_POST['cbody'];
$result = $db->query("UPDATE chapter set chapter_title='$title', chapter_body='$body' where chapter_id='$id'");
}
$result = $db->query("select * from chapter");
while($row = mysqli_fetch_assoc($result)) {
$update = 'chapterid';
echo "<li id='button' class='btn' ><b id='shadow'><a href='chapter1.php?update={$row['chapter_id']}'>{$row['chapter_title']}</b></a></li></button>";
}
?>
PHP code for displaying the input 'text' and 'textarea'.
<?php
if (isset($_POST['update'])) {
$update = $_POST['update'];
$result1 = $db->query("select * from chapter where chapter_id=$update");
while($row1 = mysqli_fetch_assoc($result1)) {
echo "<center>";
echo "<form class='form' method='POST'>";
echo "<h2>Update Form</h2>";
echo "<hr/>";
echo"<input class='input' type='hidden' name='cid' value='{$row1['chapter_id']}'/>";
echo "<br />";
echo "<label>" . "Chapter Title:" . "</label>" . "<br />";
echo"<input class='input' type='text' name='ctitle' value='{$row1['chapter_title']}' />";
echo "<br />";
echo "<label>" . "Chapter Body:" . "</label>" . "<br />";
echo "<textarea rows='15' cols='95' name='cbody'>{$row1['chapter_body']}";
echo "</textarea>";
echo "<br />";
echo "<input class='submit' type='submit' name='submit' value='update' />";
echo "</form>";
echo "</center>";
}
}
if (isset($_POST['submit'])) {
echo '<div class="form" id="form3"><br><br><br><br><br><br>
<Span>Data Updated Successfuly......!!</span></div>';
}
?>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div><?php
mysqli_close($db);
?>
if (isset($_POST['update'])) {
This line should stay $_GET['update'], because "update" is not part of you form, but part of the url:
<a href='chapter1.php?update={$row['chapter_id']}'

Show 'Google Books` items with PHP

I'm studying a way to use the Google Books API.
Using this code have the expected result.
$page = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=julio+verne&maxResults=40");
$data = json_decode($page, true);
for($a = 0 ; $a <= 39 ; $a++) {
$img = $data['items'][$a]['volumeInfo']['imageLinks']['thumbnail'];
print '<img src="'.$img.'" alt="ScanLine"/>';
echo '<br>';
echo "Title = " . $data['items'][$a]['volumeInfo']['title'];
echo '<br>';
echo "Authors = " . #implode(",", $data['items'][$a]['volumeInfo']['authors']);
echo '<br>';
echo "Editora = " . $data['items'][$a]['volumeInfo']['publisher'];
echo '<br>';
echo "id = " . $data['items'][$a]['id'];
echo '<br>';
echo "Resumo = ";
echo "<p>" . $data['items'][$a]['volumeInfo']['description'];
echo '</p><br>';
}
On the other hand, implementing and using the code form the code does not work.
My page with form have this code:
<form action="action.php" method="POST">
<div class="form-group">
<div class="campos">
<label>
Search
</label>
<input type="text" name="search" style="margin-right: 10px; width:250px; float:left" class="input-field" placeholder="Title, Author..." />
<input type=hidden name=numResults value="&maxResults=40">
<button type="submit" id="search" class="btn btn-default">Search</button>
</div>
</div>
</form>
And my action have this code:
$var1 = "https://www.googleapis.com/books/v1/volumes?q=";
$var2 = urlencode($_POST['search']);
$var3 = "&maxResults=40";
$str = str_replace(" ", "+", $var2);
$page = $var1.$str.$var3;
$data = json_decode($page, true);
echo $page;
echo '<br>';
for($a = 0 ; $a <= 39 ; $a++) {
$img = $data['items'][$a]['volumeInfo']['imageLinks']['thumbnail'];
print '<img src="'.$img.'" alt="ScanLine"/>';
echo '<br>';
echo "Title = " . $data['items'][$a]['volumeInfo']['title'];
echo '<br>';
echo "Authors = " . #implode(",", $data['items'][$a]['volumeInfo']['authors']);
echo '<br>';
echo "Editora = " . $data['items'][$a]['volumeInfo']['publisher'];
echo '<br>';
echo "Resumo = ";
echo "<p>" . $data['items'][$a]['volumeInfo']['description'];
echo '</p><br>';
}
What must be wrong?
Any advise?
Thanks from Brazil
You are not calling file_get_contents() in the second example. So $page is just the url.
$page = file_get_contents($var1.$str.$var3);

Collect data from <select> tag using PHP

I tried to use the data from this form which is located in my main page - index.php.
<center>
<form action="search.php" method="post">
<input type="text" name="search" size="30" />
<select name='wheretosearch'>
<option value='Articles'>Articles</option>
<option value='Users'>Members</option>
</select>
<input type="submit" value="Search" />
</form>
</center>
This is the main part of search.php code:
include "all/config.php";
$search = $_REQUEST['search']; //Getting the words
$split = split(" ",$search); //If there is more than one I spit them.
foreach ($split as $array => $value)
{ $NewResult .= $value;
}
$wheretosearch = $_POST['wheretosearch'];
if ($wheretosearch = 'Articles')
{$Results = mysql_query("SELECT * FROM bgarticles WHERE title LIKE '%$value%' OR description LIKE '%$value%' OR text LIKE '%$value%' OR tags LIKE '%$value%' OR date LIKE '%$value%' OR author LIKE '%$value%' OR ip LIKE '%$value%' ");
while($row = mysql_fetch_array($Results))
{
echo "<div class='top'>";
echo "<span class='title'>";
echo "<a href=details.php?id=$row[id]>";
echo $row['title'];
echo "</a>";
echo "</span> <br><br>";
echo "<span class='author'>";
echo $row['author'];
echo "</span>";
echo "<span class='date'> Date: ";
echo $row['date'];
echo "</span> <br><br><br>";
echo "<br><br></div>" ;
echo "<div class='bottom'><br><br></div>";
}
}
if ($wheretosearch = 'members')
{$Results2 = mysql_query("SELECT * FROM members WHERE username LIKE '%$value%' OR firstname LIKE '%$value%' OR lastname LIKE '%$value%' ");
while($row2 = mysql_fetch_array($Results2))
{
echo "<div class='top'>";
echo "<span class='title'>";
echo "<a href=details.php?id=$row2[id]>";
echo $row2['username'];
echo "</a>";
echo "</span> <br><br>";
echo "<span class='author'>";
echo $row2['firstname'];
echo "</span>";
echo "<span class='date'> Date: ";
echo $row2['date'];
echo "</span> <br><br><br>";
echo "<br><br></div>" ;
echo "<div class='bottom'><br><br></div>";
}
}
No matter I do it always shows data from both mysql tables. Why?
You're using a single equals sign, which sets a variable. A double equals compares.
if ($wheretosearch = 'members') {
// $wheretosearch is now (always) set to 'members'
// this will always trigger
}
if ($wheretosearch == 'members') {
// this will only trigger when the above is true
}
Use == instead of = in your if statements.
= != ==
Your if conditions contain assignments, not comparison operations.
Common mistake, plenty of blogs contain easy ways to avoid it.
Honestly: http://bobby-tables.com/
(and then check your if-clauses, you're using assignments (=) instead of comparisons (==))
You're missing an equal sign, so it's making an assignment instead of testing for equality.
if ($wheretosearch = 'Articles')
should be...
if ($wheretosearch == 'Articles')
Also: you're not escaping your queries, so your database would be easily hackable. Before using your variables in a query, escape them like so:
$wheretosearch = mysql_real_escape_string($wheretosearch);

Categories