Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed yesterday.
Improve this question
I am currently working on a mailing/messaging system. Now I want to send a message, but I want to add more recipients, but I can't do this. It would be kind if one of you would like to help me.
I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.
(My English is not so good, so sorry if there are spelling mistakes).
// JS for the to-tags.
function parse() {
var tag_input = document.getElementById("tags_input");
var tags = document.getElementById("tags");
//
var input_val = tag_input.value.trim();
var no_comma_val = input_val.replace(/,/g, "");
//
if (input_val.slice(-1) === "," && no_comma_val.length > 0) {
var new_tag = compile_tag(no_comma_val);
tags.appendChild(new_tag);
tag_input.value = "";
}
}
function compile_tag(tag_content) {
let a = -3;
var tag = document.createElement("p");
//
var text = document.createElement("span");
text.setAttribute("class", "badge badge-success");
text.setAttribute("id", tag_content);
text.innerHTML = tag_content;
//
var remove = document.createElement("i");
remove.setAttribute("class", "fa fa-remove");
remove.setAttribute("id", "remove");
remove.onclick = function() {this.parentNode.remove();};
//
tag.appendChild(remove);
tag.appendChild(text);
//
return tag;
}
// HTML AND PHP
<?php
session_start();
include_once("error.php");
include "db.php";
if (isset($_SESSION['login'])){
?>
<?php
$functions = array('newMessage');
if (isset($_GET['action'])){
if (in_array($_GET['action'], $functions)){
function newMessage(){
// when on the button press
if (isset($_POST['button_send'])) {
global $conn;
// take the user id
$from = $_SESSION['id'];
// create table one
$create = "INSERT INTO `messages` SET
`messageFrom` = '$from',
`messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."',
`messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."'
";
// when table one is created make table to. **This is where things go wrong**
if (mysqli_query($conn, $create)){
if ($create = true){
$read = mysqli_query($conn, "SELECT * FROM `blog` WHERE `messageSubject` = '$_POST['inp_subject']' AND `messageFrom` = '$from' ");
$data = mysqli_fetch_assoc($read);
$id = $data['messageId'];
$create = "INSERT INTO `receivers` SET
`messageId` = '$id',
`messageSubject` = '".mysqli_real_escape_string($conn, $_POST['inp_subject'])."',
`messageBody` = '".mysqli_real_escape_string($conn, $_POST['textarea_body'])."'
"; if (mysqli_query($conn, $create)){
echo "fine";
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}else{
echo 'Sorry, '.mysqli_error($conn);
}
}
?>
<form method="post">
<div class="from_group">
<input type="text" name="inp_to" id="inp_to" placeholder="Give the name(s)..." required>
<label>To:</label>
</div>
// The TO-input
<div class="container">
<div class="col-sm-6">
<input onkeyup="parse();" type="text" id="tags_input" placeholder="comma-separated tags" maxlength="100" class="form-control">
</div>
// the to tags
<div class="col-sm-6" id="tags" name="tags">
</div>
</div>
<script src="js/input_comma.js"></script>
<div class="from_group">
<input type="text" placeholder="Give the subject..." name="inp_subject" required>
<label>Subject: </label>
</div>
<div class="from_group">
<textarea name="textarea_body" rows="10" cols="30">
</textarea>
</div>
<button name="button_send"> Send </button>
</form>
</div>
<?php
}
echo $_GET['action'] ();
}else{
functionNotfound();
}
}
?>
<?php
}else{
notLoggedin();
}
?>
Already thanks for the help.
I would like each message(body, from and subject) to be in a separate table. And that the message id and to(and if there are multiple recipients that it creates multiple rows.) come in another table.
Related
I want to explain my doubt with an example
Lets say i got movie database where i stored info related to particular movie in each row.
Lets say i got two rows in my database
1) Titanic 1997 Romance, Thriller
2) Avatar 2009 Action, Fantasy, Romance
I have homepage.php where movie images with text below it are displayed as gallery and i got a movieinfo.php page where all the info about movie is present.
Ex :
Title : "Titanic"
Release Date : "1997"
Genre : "Romance, Thriller"
etc
Now when i clicked on titanic image(which is in my homepage.php) it should redirect to movieinfo.php and get the titanic info from database with id and should display related info of titanic in those double quotes " " (nothing should be changed in movieinfo.php other than those values placed in double quotes).
And same should be happen when i click on avatar image
I tried to change that info with php but it gets last imported data from database and displays that info.
After some research i found that it is possible with AJAX but i am absolute beginner with AJAX. Need someone's help to know the logic and it will be more helpful if you give me small code with above example
Thank you
I have created example code so that i can get help from you
Lets say this is my moviedb.php(which contains movie insertion php code)
<?php
$title = "";
$releaseDate = "";
$Genre = "";
if (isset($_POST['submit-btn'])) {
if (empty($_POST['title'])) {
$errors['title'] = 'Title required';
}
if (empty($_POST['genre'])) {
$errors['genre'] = 'Genre required';
}
if (empty($_POST['releaseDate'])) {
$errors['releaseDate'] = 'Release Date required';
}
$title = $_POST['title'];
$releaseDate = $_POST['releaseDate'];
$genre = $_POST['genre'];
// Check if title already exists
$sql = "SELECT * FROM movie WHERE movie_title='$title' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$errors['title'] = "Title already exists";
}
if (count($errors) === 0) {
$query = "INSERT INTO movie SET movie_title=?, movie_releaseDate=?, movie_genre=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('sss', $title, $releaseDate, $genre);
$result = $stmt->execute();
if ($result) {
$movie_id = $stmt->insert_id;
$stmt->close();
$_SESSION['movie_id'] = $movie_id;
$_SESSION['title'] = $title;
$_SESSION['releaseDate'] = $releaseDate;
$_SESSION['genre'] = $genre;
$_SESSION['message'] = 'Movie has been inserted succesfully!';
header('location: movieinsertion.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not insert movie";
}
}
}
?>
This is movieinsertion.php (which contains form to enter movie details to database )
<form action="movieinsertion.php" method="post">
<label for="title"><b>Title : </b></label>
<input type="text" placeholder="Enter Title" name="title" required>
<label for="releaseDate"><b>Release Date : </b></label>
<input type="text" placeholder="Enter Release Date" name="releaseDate" required>
<label for="genre"><b>Genre : </b></label>
<input type="text" placeholder="Enter Genre" name="genre" required>
<div class="clearfix">
<button type="submit" class="submitbtn" name="submit-btn" id="submit-btn">Movie insert</button>
</div>
</form>
This is movieinfo.php (where movie info is displayed)
<p class="movieinfo">
<b style="font-size:20px; color:tomato;"> Title : </b> <?php echo $_SESSION['title']; ?>
<br/>
<b> Release Date : </b> <?php echo $_SESSION['releaseDate']; ?>
<br/>
<b> Genre : </b> <?php echo $_SESSION['genre']; ?>
</p>
This is homepage.php (Where movie images are placed using anchor tag)
<div class="movieimg">
<a href = "movieinfo.php"> <img src="assets/image-1.jpg" alt="Titanic" style="width:100%">
<div class="text">Titanic</div></a>
</div>
<div class="movieimg">
<a href = "movieinfo.php"> <img src="assets/image-2.jpg" alt="Avatar" style="width:100%">
<div class="text">Avatar</div></a>
</div>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am using php and mysql to update user data inside of the database as admin, i have a text box which allows the admin to input approved or not approved, now i want to try change the text box for the approved or not approved into a check box where the admin can just click on the check box approved and the data will be updated according to the user which was selected as im not really sure how to go about it. thanks
<?php
require('connection.php');
if (isset($_POST['submit'])) {
$prescription = $_FILES['prescription']['name'];
$image_tmp = $_FILES['prescription']['tmp_name'];
move_uploaded_file($image_tmp,"medical-prescription/$prescription");
$sql = $conn->prepare("UPDATE users SET approved=?,prescription=? WHERE id=?");
$approved=$_POST['approved'];
$sql->bind_param("ssi",$approved, $prescription,$_GET["id"]);
if($sql->execute()) {
$success_message = "Edited Successfully";
} else {
$error_message = "Problem in Editing Record";
}
}
$sql = $conn->prepare("SELECT * FROM users WHERE id=?");
$sql->bind_param("i",$_GET["id"]);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
}
$conn->close();
?>
<?php if(!empty($success_message)) { ?>
<div class="success message"><?php echo $success_message; ?></div>
<?php } if(!empty($error_message)) { ?>
<div class="error message"><?php echo $error_message; ?></div>
<?php } ?>
<form method="post" action="" enctype="multipart/form-data">
<label>approved</label>
<input type="text" name="approved" class="txtField" value="<?php echo $row["approved"]?>">
<label>Medical prescription</label>
<input type="file" name="prescription" id="prescription" required/><br>
<input type="submit" name="submit" value="Submit" class="demo-form-submit">
</form>
You can do it this way:
Change HTML:
<input type="checkbox" name="approved" class="txtField" value="<?php echo $row["approved"]?>"> Approved?
php:
Replace this:
...
$approved=$_POST['approved'];
...
with:
...
$approved=(isset($_POST['approved'])) ? $_POST['approved']: "Not approved"; // Or any other text value what you use
...
Here is formatted code:
<?php
require('connection.php');
if (isset($_POST['submit'])) {
$prescription = $_FILES['prescription']['name'];
$image_tmp = $_FILES['prescription']['tmp_name'];
move_uploaded_file($image_tmp,"medical-prescription/$prescription");
$sql = $conn->prepare("UPDATE users SET approved=?,prescription=? WHERE id=?");
//HERE WE CHANGE
$approved=(isset($_POST['approved'])) ? $_POST['approved']: "Not approved";
$sql->bind_param("ssi",$approved, $prescription,$_GET["id"]);
if($sql->execute()) {
$success_message = "Edited Successfully";
} else {
$error_message = "Problem in Editing Record";
}
}
$sql = $conn->prepare("SELECT * FROM users WHERE id=?");
$sql->bind_param("i",$_GET["id"]);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
}
$conn->close();
?>
<?php if(!empty($success_message)) { ?>
<div class="success message"><?php echo $success_message; ?></div>
<?php } if(!empty($error_message)) { ?>
<div class="error message"><?php echo $error_message; ?></div>
<?php } ?>
<form method="post" action="" enctype="multipart/form-data">
<label>approved</label>
<input type="checkbox" name="approved" class="txtField" value="<?php echo $row["approved"]?>"> Approve?
<label>Medical prescription</label>
<input type="file" name="prescription" id="prescription" required/><br>
<input type="submit" name="submit" value="Submit" class="demo-form-submit">
</form>
Here is the test:
$('form').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
alert("Submitted data: {" + data + '}');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="approved" class="txtField" value="Yes"> Approved?
<button type="submit" name="submit" value="submit">Submit</button>
</form>
I am creating a simple site to keep records of users, customers, suppliers, etc.
I have created the forms to register clients and users using single forms capturing data through $ _POST form method
So far I have not had problems since the INSERTS are done on singles table which PK is an AutoIncremented field
In the code shown below, my goal is to let users create a vendor (name, phone number, email, address) as well as assign 1 or many vendor-category. This information is contained in one form
vendors, vendors-categories, users, etc. are stored in a MySQL database with the structure shown:
There is something wrong about my code after successfully create vendor and I am not sure how to solve the part that manages insertions in the join table (tblprovxrubro)
Code
<?php
session_start();
//available for admin, power-users and role-4
if ($_SESSION['rol'] ==2) {
header("location: ./");
}
include "../conexion.php";
if (!empty($_POST)) {
$alert='';
if (empty($_POST['razonSocial'])|| empty($_POST['email'])) {
$alert='<p class="msg_error">Vendor name and email must not be blank.</p>';
}else{
$razonSocial = $_POST['razonSocial'];
$email = $_POST['email'];
$domicilio = $_POST['domicilio'];
$telefono = $_POST['telefono'];
$usuario_id = $_SESSION['iduser'];
$query = mysqli_query($conection,"SELECT * FROM tblprov WHERE razonSocial = '$razonSocial'");
$result = mysqli_fetch_array($query);
if ($result >0)
{
$alert='<p class="msg_error">vendor already exists.</p>';
}else{
$query_insert = mysqli_query($conection, "INSERT INTO tblprov(razonSocial, numero, domicilio, email, idUsuario)
VALUES('$razonSocial','$telefono','$domicilio','$email', '$usuario_id')");
if ($query_insert)
{
$alert='<p class="msg_save">Vendor created succesfully.</p>';
//Once vendor is created I need his ID in order to insert in table
//tblprovxrubro as many records as vendor-types selected in form
//Not sure about how to achieve this
$queryBuscaprov = mysqli_query($conection, "SELECT id FROM tblprov WHERE razonSocial = '$razonSocial'");
$result_prov = mysqli_fetch_array($queryBuscaProv);
$idProv = $result_prov['id'];
foreach ($_POST['idRubro'] as $opcionSeleccionada)
{
//This INSERT should execute as many times as vendor-types selected in form
$query2 = mysqli_query($conection, "INSERT INTO tblprovxrubro (idRubro, idProv) VALUES ('$opcionSeleccionada', '$idProv')");
}
}else{
$alert='<p class="msg_error">Error creating vendor.</p>';
}
}
}
mysqli_close($conection);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php"; ?>
<title>Registro de Proveedores</title>
</head>
<body>
<?php include "includes/header.php"; ?>
<section id="container">
<div class="form_register" name="form_register">
<h1><i class="fas fa-building"></i> Vendor List</h1>
<hr>
<form action="" method="post" class="form_register">
<div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div>
<label for="razonSocial">Razón Social</label>
<input type="text" name="razonSocial" id="razonSocial" placeholder="Razón Social">
<label for="telefono">Número Telefónico</label>
<input type="text" name="telefono" id="telefono" placeholder="Número Telefónico">
<label for="domicilio">Domicilio</label>
<input type="text" name="domicilio" id="domicilio" placeholder="Domicilio">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Email">
<?php
$query_rubro = mysqli_query($conection,"SELECT * FROM tblrubros");
mysqli_close($conection);
$result_rubro = mysqli_num_rows($query_rubro);
?>
<select name="rubro[]" id="rubro" multiple size="12">
<?php
if($result_rubro > 0)
{
while ($rubro = mysqli_fetch_array($query_rubro))
{
?>
<option value="<?php echo $rubro["idRubro"]; ?>"><?php echo $rubro["rubroDescripcion"] ?></option>
<?php
}
}
?>
</select>
<p>press Ctrl in order to select multiple options.</p>
<button name="submit" type="submit" class="btn_save"><i class="fas fa-save"></i> Crear Proveedor</button>
</form>
</div>
</section>
<?php include "includes/footer.php"; ?>
</body>
</html>
conection.php
<?php
$host = 'localhost';
$user = 'root';
$password = 'mypass';
$db = 'compras';
$conection = #mysqli_connect($host,$user,$password,$db);
mysqli_set_charset($conection,"utf8");
if(!$conection){
echo "connection error";
}
?>
file does not appear
hi guys, i having problem with my forms which i already set a value from my database which my file input doesn't appear out from database. who have idea what problem? the datatype i using for file in mysql is medium blob which stores the file in a folder called upload. first code is my editquiz.php, while second codes is my pedit.php.
<form method ="post" action = "peditQuiz.php" enctype="multipart/form-data">
<input type = "hidden" name = "quizID" id="quizID" value = "<?php echo $st_row['q_id'] ?>" >
<div class="form-group">
<h4><b>Quiz ID: <span class="text-primary"><?php echo $st_row['q_id'] ?></span> </b></h4>
</div>
<hr>
<div class="form-group">
<label>Quiz Title</label>
<input type="text" class="form-control" name = "quizTitle" id="quizTitle" value = "<?php echo $st_row['q_title'] ?>" required>
</div>
<div class="form-group">
<label>Quiz Description</label>
<input type="text" class="form-control" name = "quizDesc" id="quizDesc" value = "<?php echo $st_row['q_desc'] ?>" required >
</div>
<div class="form-group">
<label>Quiz URL (paste the link here)</label>
<input type="url" class="form-control" name = "quizURL" id="quizURL" value = "<?php echo $st_row['q_url'] ?>">
</div>
<div class="form-group">
<label>Upload new Quiz file (Max. allowed file size is 8MB)</label>
<input type="file" class="form-control" name = "quizFile" id ="quizFile" value = "<?php echo $st_row['q_file'] ?>" placeholder = "<?php echo $st_row['q_file'] ?>">
</div>
<input type="submit" class="btn btn-default" name = "btnUpdate" value = "Update">
<input type="reset" class="btn btn-default" value = "Clear">
<button type="button" style = "float:right" class="btn btn-info" >Back</button>
//Pedit.php
<?php
include("connection.php");
$userid = $_SESSION['userID'];
$title= $_POST['quiz_Title'];
$desc = $_POST['quiz_Desc'];
$url = $_POST['quiz_URL'];
$file = rand(1000, 100000). "-".$_FILES['quiz_File']['name'];
$file_loc = $_FILES['quiz_File']['tmp_name'];
$file_size = $_FILES['quiz_File']['size'];
$file_type = $_FILES['quiz_File']['type'];
$folder="files/";
move_uploaded_file($file_loc, $folder.$file);
/*
$id = $_POST['quizID'];
$sql = "SELECT * FROM quiz where quiz_id = '$id'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$count = mysql_num_rows($result);
if($count > 0){
echo "<script>alert('Quiz record already exist');window.location.href = 'addQuiz.php';</script>";
} else { */
if($url==NULL){
$sql = "insert into quiz (q_title, q_desc, q_url, q_file, admin)
values ('$title','$desc ','$url','$file','$userid ' )" ;
mysql_query($sql);
echo "<script>alert('New record created succcessfully');window.location.href = 'manageQuiz.php';</script>";
} else{
$sql = "insert into quiz (q_title, q_desc, q_url, admin)
values ('$title','$desc ','$url','$userid ' )" ;
mysql_query($sql);
echo "<script>alert('New record created succcessfully');window.location.href = 'manageQuiz.php';</script>";
}
//}
mysql_close($con);
?>
Your question is difficult to follow, but I'll try:
It looks like you are using php to dump values in your form via PHP before you load the values later with your include statement.
I'm also not sure why you are saying that you use a file-based database but also seem to include sql commands, but regardless of how you load values into "$st_row['q_id']", they must be loaded before you attempt to echo them into your html.
If you have a requirement to include the db file later for some reason, you could use javascript to push the values into the form fields after the fact.
If, however, you are looking for the results of the sql queries from an included file ... I think you'll need to specify what value you expected to load from what file and provide that code as well.
Hope that helped. Good luck. Also congrats on asking a question on stackoverflow. Looks like you're a beginner but trying hard. ;)
I am having trouble updating the posts table of my database when a user updates a blog post they have made.
Flow of events - user makes a blog post, its saved to DB then they can go back and edit it. Edit brings up a pre-filled html form populated with data from the posts table. Then the user can change the title and content and when they press update the posted values from the form should replace the title and content of the original post in posts DB all other columns remain unchanged.
Currently my database just doesn't seem to update, not sure why. Using a combination of html/php/sql/pdos to execute sql statements - getting very complex for my novice experience and any help is appreciated.
Code (UPDATE statement is at bottom and most problematic):
// begin edit post
if(isset($_GET['editPost'])) {
$editPostId = $_GET['editPost'];
$sqlEditPostCheck = <<<EOD
SELECT author, id FROM posts WHERE author = '$currentUserId'
EOD;
$stmtEditPostCheck = $pdo->prepare($sqlEditPostCheck);
$stmtEditPostCheck->execute();
$ableToEdit = false;
while ($row = $stmtEditPostCheck->fetch(PDO::FETCH_ASSOC)) {
if($editPostId === $row['id'] && $currentUserId === $row['author']) { $ableToEdit = true; }
}
if($ableToEdit === true) {
$editPost_Title = "";
$editPost_Content = "";
$sqlEditPostPreFills = <<<EOD
SELECT id, post_title, content FROM posts WHERE id="$editPostId"
EOD;
$stmtEditPost = $pdo->prepare($sqlEditPostPreFills);
$stmtEditPost->execute();
while ($row = $stmtEditPost->fetch(PDO::FETCH_ASSOC)) {
$editPost_Title = $row['post_title'];
$editPost_Content = $row['content'];
$editPostId = $row['id'];
}
$content = <<<EOD
<form action="?profile&editPost="$editPostId" method="post">
<h1>Edit Post</h1>
<div class="form-group">
<input name="Epost_title" type="text" id="Epost_title" value="$editPost_Title" class="form-control">
</div>
<div class="form-group">
<textarea class="form-control" name="Epost_content" id="Epost_content" value="" rows="6">$editPost_Content</textarea>
</div>
<div style="text-align: right;">
<button type="submit" name="update" style="width: 30%;" class="btn btn-success btn-lg">Update</button>
</div>
</form>
<hr />
EOD;
} // end IF ableToEdit
$updatedContent = "";
if(isset($_POST['Epost_content'])) { $updatedContent = $_POST['Epost_content']; }
$updatedTitle = "";
if(isset($_POST['Epost_title'])) { $updatedTitle = $_POST['Epost_title']; }
if(isset($_POST['Epost_content']) && isset($_POST['Epost_title'])) {
$sqlUpdatePost = <<<EOD
UPDATE posts SET post_title='$updatedTitle', content='$updatedContent' WHERE posts.id='$editPostId' AND posts.author='$currentUserId';
EOD;
$stmtUpdate = $pdo->prepare($sqlUpdatePost);
$stmtUpdate->execute();
}
}
// end edit post
This line look bad for me
<form action="?profile&editPost="$editPostId" method="post">
try to change it to
<form action="?profile&editPost=\"$editPostId\" method=\"post\">"