I try to make online quiz with images questions, and i need your help/advice.
My images is stored on database where have an id "image". My upload works fine, image is stored on database...but i can't show image in questions.
Here is my structure from database: http://imageshack.com/a/img923/8746/Kf16xl.jpg
And that's my code from show questions with image:
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysqli_query($connection, "SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="submit" value="Finish">
</form>';
exit();
}
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
$singleSQL = mysqli_query($connection, "SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection, "SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
The part with show images is:
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
Thank you very much for allocating your time!
Related
I have an application that where users can post announcements and comment on posts. My problem is that whenever a comment is posted, It shows up on every announcement post. How can I post comments so that they show up on that specific post?
I have 2 database tables: "announcement: id, name, announcementTitle, announcement, image" and "comment: id, post_id, name, comment" with foreign key attached to comment.
Here is my home.php where the announcements and comments are echoed
<div class="container">
<div class="mx-auto">
<?php
if (isset($_SESSION['username'])) {
echo'
<h1 style="text-decoration:underline">Post an announcement</h1>
<form method="post" action="announcement.php" enctype="multipart/form-data">
<input type="text" name="announcementTitle" placeholder="Enter Subject"><br>
<textarea name="announcementBox" rows="5" cols="40" placeholder="Enter Announcement"></textarea><br>
<input type="file" name="image" accept="image/jpeg">
<button name="announcement">Submit</button>
</form>';
}
$query = "SELECT * FROM announcement ORDER BY id DESC";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="row" style="color:black;background-color:white;border-radius:5px;padding:10px;margin-top:10px;margin-bottom:70px">';
echo '<div class="column" style="width:100%;border:5px">';
if (isset($_SESSION['username'])) {
echo '<form method="post" action="announcement.php">';
echo "Posted by " .$row["name"]. " click X to delete:";
echo '<input type="hidden" name="postID" value="'.$row['id'].'">';
echo '<button name="delete" style="float:right">X</button>';
echo '</form>';
}
echo $row['announcementTitle'].'<br>';
echo $row['announcement'].'<br>';
echo '<img width="20%" src="data:image;base64,'.$row['image'].'"alt="Image" style="padding-top:10px">';
echo'
<form method="post" action="comment.php">
<textarea name="commentbox" rows="2" cols="50" placeholder="Leave a Comment"></textarea><br>
<button name="comment">Submit</button>
</form>';
echo "Comments:<p><p>";
echo " <p>";
$find_comment = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($con,$find_comment);
while ($row = mysqli_fetch_array($res)) {
echo '<input type="hidden" name="postID" value="'.$row['post_id'].'">';
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name: $comment<p>";
}
if(isset($_GET['error'])) {
echo "<p>100 Character Limit";
}
echo '</div></div>';
}
?>
</div>
</div>
Here is comment.php where comments are put in the database
<?php
session_start();
$con = mysqli_connect('localhost', 'root', 'Arv5n321');
mysqli_select_db($con, 'userregistration');
$namee = '';
$comment = '';
$comment_length = strlen($comment);
if($comment_length > 100) {
header("location: home.php?error=1");
}else {
$que = "SELECT * FROM announcement";
$res = mysqli_query($con,$que);
while ($row = mysqli_fetch_array($res)) {
$post_id = $row['id'];
}
$namee = $_SESSION['username'];
$comment = $_POST['commentbox'];
$query = "INSERT INTO comment(post_id,name,comment) VALUES('$post_id','$namee','$comment')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
?>
Here is announcement.php where announcements are put in the database
<?php
session_start();
//$con = mysqli_connect('freedb.tech', 'freedbtech_arvindra', 'Arv5n321', 'freedbtech_remote') or die(mysqli_error($con));
$con = mysqli_connect('localhost', 'root', 'Arv5n321', 'userregistration') or die(mysqli_error($con));
if (isset($_POST['announcement'])) {
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
date_default_timezone_set("America/New_York");
$title = $_POST['announcementTitle']." (<b>".date("m/d/Y")." ".date("h:i:sa")."</b>)";
$paragraph = $_POST['announcementBox'];
if (empty($paragraph)||empty($title)) {
header('location:home.php?error=fillintheblanks');
}else{
$nam = $_SESSION['username'];
$query = "insert into announcement(name,announcementTitle,announcement,image) values('$nam','$title','$paragraph','$image')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
}else if (isset($_POST['delete'])){
$query = "delete from announcement where id='".$_POST['postID']."';";
$result = mysqli_query($con,$query);
if ($result) {
header('location:home.php?success=deleted');
} else {
header('location:home.php?error=couldnotdelete');
}
}
else {
header('location:home.php');
}
I am a little new to PHP so any help is good.
I have a form with uploading multiple files.
When I upload let's say two images and when I click submit, the images are displayed properly, but when I edit some other input and click submit button, the images are gone.
Here's my code:
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$id = $row->id;
$title = $row->title;
$body = $row->body;
$status = $row->status;
}
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$body = $_POST['body'];
$image = $_POST['image'];
$status = $_POST['status'];
//if($_FILES['image']['tmp_name']) {
if(!empty($_FILES['image']['name'])) { //Edit
// delete old image
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$old = $row->filename;
unlink('../uploads/' . $old);
}
$query = "DELETE FROM postimage WHERE post_id = $id";
$delete_images = $db->query($query);
foreach($_FILES['image']['tmp_name'] as $key => $tmp_name) {
$filename = rand(100,999)."-".$_FILES['image']['name'][$key];
$filetmp = $_FILES['image']['tmp_name'][$key];
if(move_uploaded_file($filetmp, '../uploads/' . $filename)) {
$query = "INSERT INTO postimage(post_id, filename) ";
$query .= "VALUES($id, '$filename')";
$insert_images = $db->query($query);
}
}
}
$query = "UPDATE posts SET ";
$query .= "title = '$title', ";
$query .= "body = '$body', ";
$query .= "status = '$status', ";
$query .= "updated = now() ";
$query .= "WHERE id = $id ";
$update_post = $db->query($query);
//header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title">Post title</label>
<input type="text" value="<?php echo $title; ?>" name="title">
</div>
<div class="form-item">
<label for="body">Post body</label>
<textarea id="editor" name="body" rows="10" cols="30"><?php echo $body; ?></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<?php
$query = "SELECT * FROM postimage WHERE post_id = $id";
$select_image = $db->query($query);
while($row = $db->fetch_object($select_image)) {
$filename = $row->filename;
echo '<img width="100" height="70" src="../uploads/' . $filename . '">';
}
?>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="<?php echo $status; ?>"><?php echo $status; ?></option>
<?php
if($status == 'published') {
echo '<option value="draft">draft</option>';
} else {
echo '<option value="published">published</option>';
}
?>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Update post">
</div>
</form>
When I'm using simple form with uploading a single image and connects with only one table, I usually fix that problem with this:
if(empty($image)) {
$query = "SELECT * FROM posts WHERE id = $id";
$result = $db->query($query);
while($row = $db->fetch_object($result)) {
$image = $row->image;
}
}
How can I solve this problem using multiple upload input?
EDITED: change it to
if(!empty($_FILES['image']['name']))
because $_FILES['image']['tmp_name'] always return path to temp so jou cannot test it for empty
I've solved the problem.
When using multiple file upload, the if statement has to be changed, so in this case it should be: if(!empty($_FILES['image']['tmp_name'][0]))
I need help with loading specific info for the image that has been clicked. The info is stored into a MYSQL database.
I need to determin which image was clicked, and obtaining the images
ID
Then fetch the information about that image from the database
And the echo out the information about the image
link to image of the database structure: https://www.dropbox.com/sh/8xrifn64psmc9qh/AAA5j_eous8sBpg4WP0dgrmya?dl=0
Thanks! This is the line of code i use to load the images from the database.
$sql="SELECT * FROM klubbar ORDER BY namn ASC";
$res = mysql_query($sql);
if (!$res) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="klubbar"><img src="'.$row['bild'].'"alt="'.$row['namn'].'"title="'.$row['namn'].'"/></div>';
}
PHP:
$sel_club = $_GET['klub'];
$sql="SELECT * FROM klubbar ORDER BY namn ASC";
$res = mysql_query($sql);
if (!$res) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if($sel_club)
{
$sqlC= "SELECT * FROM klubbar WHERE namn ='$sel_club'";
$resC= mysql_query($sqlC);
if($rowC = mysql_fetch_assoc($resC))
{
$id = $rowC['id'];
$namn = $rowC['namn'];
$bild = $rowC['bild'];
$lank = $rowC['lank'];
$alder = $rowC['alder'];
$dresscode = $rowC['dresscode'];
echo 'Klub: '.$namn.'<br>Webbsida: '.$lank.'<br>Åldersgräns: '.$alder.'+ <br> Dresskod: '.$dresscode;
echo
'<form method="post" action="anmalan.php">
<label name="namn">Namn:</label>
<input type="text" name="namn" placeholder="Förnamn Efternamn"/><br>
<label name="antalGuess">Antal gäster</label>
<select>
<option>+0</option>
<option>+1</option>
<option>+3</option>
<option>+4</option>
<option>+5</option>
<option>+6</option>
</select><br>
<label name="mejl">E-post:</label>
<input type="text" name="mejl" placeholder="example#ex.com"/><br>
<label name="telefon">Mobilnr:</label>
<input type="text" name="telefon" placeholder="07x xxx xx xx"/><br>
<input type="submit" name="submit" value="Skicka" />
</form>';
}
else
{
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
}
}
else
{
while ($row = mysql_fetch_assoc($res))
{
$id = $row['id'];
$namn = $row['namn'];
$bild = $row['bild'];
$lank = $row['lank'];
$alder = $row['alder'];
$dresscode = $row['dresscode'];
echo '<div class="klubbar" ><img src="'.$bild.'"alt="'.$namn.'"title="'.$namn.'"/></div>';
}
}
I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.
I have the following code (below) to that loads the likes for a specific status (for dynamic use), it works if a user is liking their own post. But if a user is liking someone elses, it epically fails.
My code:
<?php
mysql_connect ('localhost', 'funding9_joeb', 'Brailsf0rdJ0e');
mysql_select_db ('mingle');
include('../includes/ts.php');
$_COOKIE['wds'];
$ssid = $_COOKIE['wds'];
$lu = "SELECT * FROM mingle_sessions WHERE sid = '$ssid' LIMIT 1";
$luq = mysql_query($lu) or die (mysql_query());
while($uidr = mysql_fetch_assoc($luq)) {
$uid = $uidr['uid'];
}
$sql = "SELECT * FROM users WHERE uid = '$uid' LIMIT 1";
$s = htmlentities(strip_tags(stripslashes($_GET['sid'])));
$result = mysql_query($sql) or print ("Can't select entry from table mingle_usr.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$fname = stripslashes($row['fname']);
$sname = stripslashes($row['sname']);
$dp = $row['dp'];
}
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$sql = "SELECT * FROM mingle_likes WHERE byuid = '$uid' AND onuid = '$s' AND type = 'status'";
$sr = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($sr) >= 1) {
$re = ("SELECT id as id, status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' AND sid = '$s' ORDER BY timestamp DESC LIMIT 1"); //query
$result = mysql_query($re) or die (mysql_error());
while($st = mysql_fetch_assoc($result)) {
$status = nl2br($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
$id = $st['id'];
}
$like = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num FROM mingle_likes WHERE onuid = '$sid' AND type = 'status' AND byuid != '$uid'"));
$likes = ceil($like['num']);
$haslike = mysql_fetch_array(mysql_query("SELECT COUNT(*) as nu FROM mingle_likes WHERE onuid = '$sid' AND type = 'status' AND byuid = '$uid'"));
$hasliked = ceil($haslike['nu']);
?>
<script type="text/javascript" src="js/ld_s.js"></script>
<form action='ld.php' method='post' id='ls' style='display:inline; border:0px; margin: 0 0 0 0; padding: 0 0 0 0;'>
<input type="hidden" class="do_<?php echo $sid; ?>" name="onuid" value="<?php echo $sid; ?>" />
<input type="hidden" class="db_<?php echo $sid; ?>" name="byuid" value="<?php echo $uid; ?>" />
<input type="hidden" class="dp_<?php echo $sid; ?>" name="uid" value="<?php echo $uid; ?>" />
<input type="hidden" class="dt_<?php echo $sid; ?>" name="type" value="status" />
<?php
if($hasliked == 1) {
?>
<label>You <?php if($likes >= 1) { echo "and " . $likes . " other people like this"; } else{ echo "liked this |"; }?></label><input type="submit" id="like" class="<?php echo $sid; ?>" name="submit" value="Unlike" />
<?php
}
else {
?>
<label><?php if($likes >= 1) { echo $likes . " people like this |"; }?></label><input type="submit" id="like" class="<?php echo $sid; ?>" name="submit" value="Like" />
<?php
}
?>
</form>
<?php echo time_since($td); ?>
<?php
}
?>
The errors are as follows:
( ! ) Notice: Undefined variable: sid in C:\wamp\www\mingle\ajax\loadslikes.php on line 47
and then the same again for every occurrence of $sid.
I haven't got a clue why at all, like I say, it works perfectly for the user liking his/her own post, just not others.
Any ideas? :-/