Update SQL Statement with id=%d not working - php

Hi for some reason my update statement is not working, most probably because of the id=%d, its not getting the id for the statement i think but its finding the id because it is listed in the url (shown Below). What is the problem please ?
This works when i Insert a number for the id, example : id=77, so most probably the problem is the %d how can i get it to find the id with the %d ?
http://localhost/test/edit.php?id=77
<?php
ob_start();
session_start();
include_once 'logindb.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
if((isset($_POST['submit']))){
if((!isset($_POST['title'])) || (!isset($_POST['times'])) ){
echo "All values must be set";
}
else{
$title = $_POST['title'];
$times = $_POST['times'];
$film_id = $_GET['id'];
$upfile = 'Uploads/posters/'.$_FILES['userfile']['name'];
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile)){
echo "File moved into folder";
header( "Location: index.php" ) ;
}
else{
echo "Problem: could not move image file to destination directory";
}
$upfile2 = 'Uploads/trailers/'.$_FILES['userfile2']['name'];
$format1 = "UPDATE films SET titles = '$title', ftimes = '$times', poster = '$upfile', trailer = '$upfile2' WHERE id = %d";
$query = sprintf($format1, $film_id );
$result = mysqli_query($conn, $query)
or die("Error in query: ". mysqli_error($conn));
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Empire.css"/>
<script type="text/javascript" src="script.js"> </script>
<title>Movie Form</title>
</head>
<body class="formola">
<div class="form-style-5">
<p class="top"> List Movies </p>
<form method = "post" action="edit.php" enctype="multipart/form-data">
<fieldset>
<legend><span class="number">1</span> Details </legend>
<input type="text" name="title" placeholder="Movie Title">
<input type="text" name="times" placeholder="Times">
</fieldset>
<fieldset>
<legend><span class="number">2</span> Attachments </legend>
<div class="form-group ">
<label> Film Poster <br> </label>
<input type="hidden" class="form-control" name="MAX_FILE_SIZE" value="100000000">
Upload this Film Poster: <br> <input name="userfile" id="userfile" type="file"> <br>
<input type="hidden" class="form-control" name="MAX_FILE_SIZE" value="10000000">
Upload this Trailer: <br> <input name="userfile2" id="userfile2" value="10000000" type="file"> <br>
</div>
</fieldset>
<input type="submit" name = "submit" value="Upload" />
</form>
</div>
</body>
</html>

Related

Form within PHP not showing up on page

I have a form that I am trying to use to reset passwords. I can get it to send the email out and I can click the link, but when I click the link all I get is the header. My form is not showing. I am extremely new to all of this. Any help will be much appreciated. I did search through some other posts, but none of them seemed to get me any closer to the right answer. Everything seems to work as it should, I just can't get my form to display so that I can enter the information.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reset Password Form</title>
</head>
<body>
<div class="container"><h2>Reset New Password Here</h2>
<?php
if($_GET['email'] && $_GET['token']) {
$conn = mysqli_connect("localhost", "root", "", "user");
// Check connection
if($conn === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$email = $_GET['email'];
$token = $_GET['token'];
$query = mysqli_query("SELECT * FROM `customers` WHERE `reset_link_token`='".$token."' and `emailaddress`='".$email."';");
$current_date = date("Y-m-d H:i:s");
if (mysqli_num_rows($query) > 0) {
$row = mysqli_fetch_array($query);
if($row['expiry_date'] <= $current_date) { ?>
<form action="update-password.php" method="post">
<input name="email" type="hidden" value="<?php echo $email; ?>" />
<input name="reset_link_token" type="hidden" value="<?php echo $token; ?>" />
<div class="form-group"><label for="new-password">Password</label>
<input id="new-password" name="password" type="password" /></div>
<div class="form-group"><label for="confirm-password">Confirm Password</label>
<input id="confirm-password" name="confirm_password" type="password" /></div>
<input class="submit-btn" name="submit" type="submit" />
</form>
<?php }
} else {
echo "This forget password link has been expired";
}
}
?>
</div>
</body>
</html>

My posts are not making it to the database, any ideas?

I'm following a tutorial by mmtuts on youtube to show how to post comments to a myphpadmin database. All of my code is exactly the same as his, but I'm working from a different starting point becuase I already had a website I was working on and I just wanted to add the new code.
Basically, the video showed the code working flawlessly and my posts do not show up in the database like his did.
https://www.youtube.com/watch?v=4pPGOF5MI4U
".setComments($conn)." on the second document of code is blue instead of white like in the video.
<?php
require 'includes/dbh.inc.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="This is an example of a meta description. This will often show up in search results.">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>TAG</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<div id="headerContainer">
<?php
if (isset($_SESSION['userID'])) {
$id = $_SESSION['userID'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['status'] == 0) {
$filename = "profilepics/profile".$id."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<div class=userPicture><img src='profilepics/profile".$id.".".$fileactualext."?".mt_rand()."'></div>";
}
else {
echo "<div class='userPicture'><img src='profilepics/noUser.png'></div>";
}
}
echo '
<div class="userName">'. $_SESSION['userUserName'] .'</div>
<div id="logoutForm">
<form action="includes/logout.inc.php" method="post">
<button type="Submit" name="logout-submit">Logout</button>
</form>
</div>
<div class="upload">
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">Profile Image</button>
</form>
</div>
';
}
else {
echo '
<div class="userPicture"><img src="profilepics/noUser.png"></div>
<div class="userName">You are not logged in!</div>
<div id="loginForm">
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail">
<input type="password" name="password" placeholder="Password">
<button type="Submit" name="login-submit">Login</button>
</form>
</div>
<div id="signupForm">
or Signup
</div>
';
}
?>
</div>
<?php
require "header.php";
date_default_timezone_set('America/Chicago');
include 'includes/comments.inc.php';
?>
<div class="homeBody">
<p>Starting Filler</p>
<p>-</p>
<p>-</p>
<p>-</p>
<video width="320" height="240" controls>
<source src="videos/sample.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
?>
<?php
function setComments($conn) {
if (isset($POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', '$date', '$message')";
$result = $conn->query($sql);
}
}
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "thisisnotmyactualpassword";
$dBName = "tagloginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
All I want is for the posts to make it into the database.
Try making a separate PHP-file and have your action attribute inside the form tag point to it. Right now it looks like you are running the function in the action attribute. In the PHP-file you can run your PHP function and write the PHP you need.
EX:
<form method='POST' action="includes/comments.php">
I was missing the "_" in $_POST on the 3rd page of code

Insert images into a database

Im trying to upload an image to a mysql database, but when I upload the image I receive the message of confirmation, but when i check my database the image row is empty, what am I doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name']));
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ;
if ($connect->query($sql) === TRUE) {
echo "informação atualizada";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
<html>
<body>
<div class="formulario" style="width: 100%; height: 100%;">
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10
border:thin; border-style:none;">
<label> Atualizar dados </label><br>
Numero: <input type="text" name="num" value=""><br>
Texto: <input type="text" name="texto" value=""><br>
Imagem: <input type="file" name="imagem" value=""><br>
<input type="submit" name="submit" value="enviar">
<input type="reset" value="limpar">
</form>
</div>
</body>
</html>
Besides all the comments stating "You shouldn't store files in tables because...", this is what works (with PHP 7):
<?php
if(isset($_POST['submit'])) {
var_dump($_FILES);
$dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "");
$stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)");
$stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name'])));
}
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="fileinput"><br>
<button name="submit">Upload</button>
</form>
Possible error sources:
$connect->query($sql) === TRUE should be $connect->query($sql) !== false
The entry you want to UPDATE does not exist
imagem='{$image}' is a rather "hacky" way do insert variables, use concatenation: $sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;
Hope this helps.

Submitting HTML form to PHP file

I have created two files on remote server. One is html form which asks to enter some fields and another is a php file which will get all the data and insert into the database.
For this from html file on click of submit button I am calling php file, but the file is not getting execute I think because when I click on submit it again reloads the same html page.
html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form method="post" >
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br>
Enter option 2 : <input name="opt2" type="input"> <br><br>
Enter option 3 : <input name="opt3" type="input"> <br><br>
Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value = "Submit" onClick = "uploadQuestion.php">
</form>
</body>
</html>
php file:
<?php
$question=$_POST['question'];
$option1=$_POST['opt1'];
$option2=$_POST['opt2'];
$option3=$_POST['opt3'];
$option4=$_POST['opt4'];
$ans=$_POST['ans'];
$db_server = mysql_connect("address","username","pass");
if(!$db_server) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question','$option1',$option2,$option3,$option4,$ans)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
I also tried this way :
<input type="submit" value = "Submit" onClick = "http://address/uploadQuestion.php">
But nothing is working. Whats going wrong here? I am a beginner in web development,, can anyone help please? Thank you..
EDIT :
$database = new Database('addredd','username','pass','handbook');
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("insert into questions(question,answer_a,answer_b,answer_c,answer_d,answer) values(?,?,?,?,?,?)");
$stmt->execute(array($question,$option1,$option2,$option3,$option4,$ans));
I tried to use pdo statement but getting this error :
Fatal error: Class 'Database' not found in /var/www/html/uploadQuestion.php on line 12
EDIT2 :
I am trying to upload one file on server and want to save it in database also, so for this I have created 2 files one is index.php and another is uploadFile.php.
As you shown now I used pdo for this but when I click on upload image again same page is getting load.
index.php
<form action="index.php" method="post" enctype="multipart/form-data">
<p> Select image to upload:</p>
<input name = "file" type="file" id="fileToUpload"><br><br>
Enter chapter name :
<input name = "chapterName" type = "text"><br><br>
<input type="submit" value = "Upload Image">
</form>
<?php
if (isset($_FILES['file']['tmp_name']))
{
$ch = curl_init();
$cfile = new CURLFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name']);
$data = array("myfile" => $cfile);
curl_setopt($ch, CURLOPT_URL, "http://host/NewProject/uploadFile.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOTP_POSTFIELDS, $data);
$response = curl_exec($ch);
if($response == true)
{
echo "File posted";
}
else{
echo "Error: " . curl_error($ch);
}
}
?>
uploadFile.php
<?php
ini_set('display_errors', 1);
if(isset($_FILES['myfile']['tmp_name']))
{
$path = "files/" . $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], $path);
$chapterName=$_POST['chapterName'];
$dbh = new PDO('mysql:host=host;dbname=database_name','username', 'password');
$stmt = $dbh->prepare("INSERT INTO chapters (title,file) VALUES (?, ?)");
$stmt->execute(array($chapterName,$path));
if ($dbh->lastInsertId())
{
echo 'File upploaded.';
}
else
{
echo 'File could not upload.';
}
}
?>
Please help.. Thank you..
First repair your form, type="" can't be named input u can check here https://www.w3schools.com/tags/att_input_type.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="text"> <br><br>
Enter option 2 : <input name="opt2" type="text"> <br><br>
Enter option 3 : <input name="opt3" type="text"> <br><br>
Enter option 4 : <input name="opt4" type="text"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="text"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then yours php code
<?php
// mysql connection
$db_server = mysql_connect("address","username","pass");
// check for mysql connection
if(!$db_server)
{
die("Database connection failed: " . mysql_error());
}
else
{
// check if database exists
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select)
{
die("Database selection failed:: " . mysql_error());
}
}
// escape post variables
$question = mysql_real_escape_string($_POST['question']);
$option1 = mysql_real_escape_string($_POST['opt1']);
$option2 = mysql_real_escape_string($_POST['opt2']);
$option3 = mysql_real_escape_string($_POST['opt3']);
$option4 = mysql_real_escape_string($_POST['opt4']);
$ans = mysql_real_escape_string($_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
Or php with mysqli
<?php
// host, username, password, database name
$db_server = mysqli_connect("address", "username", "pass", "mlm");
// check for connection
if(!$db_server)
{
die("Database connection failed: " . mysqli_error($db_server));
}
// escape post variables
$question = mysqli_real_escape_string($db_server, $_POST['question']);
$option1 = mysqli_real_escape_string($db_server, $_POST['opt1']);
$option2 = mysqli_real_escape_string($db_server, $_POST['opt2']);
$option3 = mysqli_real_escape_string($db_server, $_POST['opt3']);
$option4 = mysqli_real_escape_string($db_server, $_POST['opt4']);
$ans = mysqli_real_escape_string($db_server, $_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysqli_query($db_server, $sql))
{
die('Error: ' . mysqli_error($db_server));
}
?>
Or php with prepared statements
<?php
// mysql connection
$dbh = new PDO('mysql:host=adress;dbname=database_name', 'username', 'password');
// escape post variables
$question = $_POST['question'];
$option1 = $_POST['opt1'];
$option2 = $_POST['opt2'];
$option3 = $_POST['opt3'];
$option4 = $_POST['opt4'];
$ans = $_POST['ans'];
$stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ( ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($question, $option1, $option2, $option3, $option4, $ans));
if ($dbh->lastInsertId())
{
echo 'Sucess.';
}
else
{
echo 'Fail.';
}
?>
Change your from code to this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br> Enter option 2 : <input name="opt2" type="input"> <br><br> Enter option 3 : <input name="opt3" type="input"> <br><br> Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Inserting data to db in PHP

I'm trying to insert somethig to db and after i write this code i get just a blank page in php. Cam you help me ? if i delete all // i get blank page if it is as now i get imput containers
<?php
function create()
{
if(isset($_POST["submit"]))
{
$db = new mysqli('localhost', 'root', 'root', 'idoctor_db');
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$password_conf = $db->real_escape_string($_POST['password_conf']);
$nick = $db->real_escape_string($_POST['nick']);
//create_new_user($username, $password, $password_conf, $nick);
//$db->query
//('
//INSERT INTO `idoctor_db`.`users` (`ID` ,`Login` ,`Password` ,`Name` ,`Level`)
//VALUES ('5 ' , 'kev5', 'roo5', 'kevkev5', ' 3 ' );
//');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<div class="container">
<form action="<?php create(); ?>" method="POST">
<input type="text" name="username" placeholder="Username..." />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="password_conf" placeholder="Confirm password" />
<input type="text" name="nick" placeholder="Nick" />
<input type="submit" value="Create" name="submit"/>
</form>
</div>
</body>
</html>
If there are no errors in running this query, you will see a blank page.
All the work is happening in the background, look at your mysql table to confirm if the insert worked.
If you want to check the outcome of the query... just do the following
$outcome = $db->query
('
INSERT INTO `idoctor_db`.`users` (
`ID` ,
`Login` ,
`Password` ,
`Name` ,
`Level`
)
VALUES
(' 4 ', ' kev4 ', ' root ', ' kevkev4 ', ' 3 ');
');
if($outcome) {
echo 'success';
} else {
echo 'failed';
}
After your edit... I see another problem in your code:
<form action="<?php create(); ?>" method="POST">
<!-- ^ This is not how you submit form data to php...
action is supposed to be a URL.. however if left blank
it will take you to the same page
Try this instead:
<?php
if(isset($_POST["submit"]))
{
$db = new mysqli('localhost', 'root', 'root', 'idoctor_db');
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$password_conf = $db->real_escape_string($_POST['password_conf']);
$nick = $db->real_escape_string($_POST['nick']);
//create_new_user($username, $password, $password_conf, $nick);
//$db->query
//('
//INSERT INTO `idoctor_db`.`users` (`ID` ,`Login` ,`Password` ,`Name` ,`Level`)
//VALUES ('5 ' , 'kev5', 'roo5', 'kevkev5', ' 3 ' );
//');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<div class="container">
<form method="POST">
<input type="text" name="username" placeholder="Username..." />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="password_conf" placeholder="Confirm password" />
<input type="text" name="nick" placeholder="Nick" />
<input type="submit" value="Create" name="submit"/>
</form>
</div>
</body>
</html>

Categories