Im trying insert user input into my databases. I want to add title and description into the advert table and an image to to the pictures table.
this is what i have come up with so far but it doesnt work at all. this is a posthandler.php page which will be called when the user presses submit. Variable at the top are assigned input names from the html page. I have both path name and blob in my pictures database at the moment to see which option will work best.
please help
<?php
session_start();
echo "You are signed in as ". $_SESSION['username'];
include 'mysql.php';
$title='title';
$des='des';
$image='image';
if(isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['title'])) {
$title= $_POST['title'];
} else {
$error = "Please enter a title for your Ad. <br />";
}
if (!empty($_POST['des'])) {
$des = $_POST['des'];
} else {
$error = "Please describe your item <br />";
}
if (!empty($_POST['image'])) {
$image=addslashes($_FILES['image']['tmp_name']);
$name=addslashes($_FILES['image']['name']);
$image=file_get_contents($image);
$image=base64_encode($image);
$filepath = "images/".$filename;
move_uploaded_file($filetmp,$filepath);
$image = $_POST['image'];
} else {
}
if (empty($error)) {
$conn= mysql_connect("localhost","km","data");
if (!$conn){
die ("Failed to connect to MySQL: " . mysql_error());
mysql_select_db("mdb_km283",$conn);
$sql = "INSERT INTO Advert (title, description) VALUES ('$_POST[title]','$_POST[des]')";
$sql2 = "INSERT INTO Pictures(image, Path) VALUES ('$_POST[image]' $filepath)";
mysql_query( $sql,$sql2, $conn );
//mysql_query( $sql2,$conn );
mysql_close($conn);
echo 'Upload successfull';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd"
>
<head>
<link rel="stylesheet" type=text/css" href="stylesheet.css">
Logout
<h1>ERROR - Please go back and fix the below:</h1>
</head>
<body>
<?php
if (!empty($error)) {
echo'<p class="error"><strong>Upload failed. Please go back and fix the below <br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} else {
echo '<meta http-equiv="refresh" content="0; URL=user.php">';
}
?>
</body>
</html>
$filename = $_FILES['image']['name'];
$filepath = 'image/' . $filename;
$filetmp = $_FILES['image']['temp_name'];
$result = move_uploaded_file($filetmp,$filepath);
if(!$result)
echo "Photo field was blank";
else
echo "uploaded";
then write ur mysql code here ....
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
after form submission form session will be saved into variables by session variable we can check right. but when i checked it out it was displaying the error
<?php
include '../includes/config.php';
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$pass = $_POST['password'];
$msg = "The email or password you entered is incorrect"; //error message
//email validation
if(empty($email) || empty($pass)){
echo $msg;
header ("refresh:5; url=index.php");
exit();
}
if(!preg_match('/#/',$email)){
echo $msg;
header ("refresh:5; url=index.php");
exit();
}
//search username and password from table users
$result = mysql_query("SELECT * FROM table_users");
$fetch = mysql_fetch_array($result);
if($email == $fetch['email'] && $pass == $fetch['pass']){
session_start();
$_SESSION['email'] = $result['email'];
$_SESSION['type'] = $result['type'];
header('refresh:2; url=../panel/index.php');
echo "Logged in..";
exit();
}
else
echo $msg;
header ("refresh:5; url=index.php");
}
else
{
header('Location:../index.php');
}
?>
This is admin code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hotel Administration</title>
<link rel="stylesheet" type="text/css" href="../../css/system.css" />
<?php
session_start();
if(!isset($_SESSION['email']))
{
die("The user must be logged in");
}
?>
</head>
<body>
i have a problem to check out the session in adminpage.. it was saying session error message help me out
SELECT * FROM table_users
thats a really bad idea, guess what happens when there are ~5k users at some time
better do
SELECT 1 FROM table_users WHERE username LIKE "$user" AND password = MD5("$password") LIMIT 1;
besides that i'd recommend to use curly blocks at else
if(!empty($fetch))
{
session_start();
$_SESSION['email'] = $result['email'];
$_SESSION['type'] = $result['type'];
header('refresh:2; url=../panel/index.php');
echo "Logged in..";
exit();
}
else
{
echo $msg;
header ("refresh:5; url=index.php");
}
I was wondering if there were any kind people out there who would be able to help me with my php conundrum! Im very very new to php and I can't quite understand how to add a comment section that is functional. I have made a database table (named 'comments') to store all of the comments that users will submit. I am not sure of these things:
1. how to connect the comment section (on php page - home.php) to my database table (comments)
2. how to make the comments that people post be posted onto the the same page - home.php
I have done something wrong as now when I type in the URL this error comes up
Parse error: syntax error, unexpected '{', expecting '(' in .../home.php on line 34
Anyway I hope someone can help me!
Thanks
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
session_destroy();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
require_once("db_connect.php");
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
}else{ $ db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
require_once('recaptcha/recaptchalib.php');
$privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$message = "";
if (!$resp->is_valid) {
$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again (reCAPTCHA said: " . $resp->error . ")";
} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission
// e.g. Validate the data
$unsafe_name = $_POST['fullname'];
}
$message .= "Thanks for your input $unsafe_name !";
echo $message;
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
$query2 = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query2) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment";
}
$query3 = "SELECT * FROM comments";
$result3 = mysqli_query($db_server, $query3);
while($array = mysqli_fetch_array($result3)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<?php echo $recaptcha_form; ?>
<input type="submit" id="submit" name="submit" value="Submit form" />
</form>
</body>
</html>
Your below statement is syntactically incorrect,
if {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
else ($comment != "") {
Should be,
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['year'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
I can't seem to correct my php error having looked at their answers and corrections. This is the error I get when the page is refreshed on the internet:
mysqli_query() expects parameter 1 to be mysqli, null given…
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
header('location: home_start.php'); //your login form
require_once("functions.php");
include_once("home_start.php");
$db_hostname = 'xxxx';
$db_database = 'xxx'; //'Your database name'
$db_username = 'xxx'; //'your username';
$db_password = 'xxx'; //'Your password';
$db_status = 'not initialised';
$str_result = ' ';
$str_options = ' ';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
$db_select = mysqli_select_db($db_server, $db_database);
}
//EXISTING DATABASE CONNECTION CODE
//if (!$db_server){
//die("Unable to connect to MySQL: " . mysqli_connect_error($db_server)); }else{ $db_status = "not connected";
//NEW SUBMISSION HANDLING CODE HERE
//if(trim($_POST['submit']) == "Submit"){
//}//EXISTING CODE (to create the options list) HERE...
//}
//require_once('recaptcha/recaptchalib.php');
//$privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
//$resp = recaptcha_check_answer ($privatekey,
//$_SERVER["REMOTE_ADDR"],
//$_POST["recaptcha_challenge_field"],
//$_POST["recaptcha_response_field"]);
//$message = "";
//if (!$resp->is_valid) {
//$message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";
//} else {
// ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission // e.g. Validate the data
//$unsafe_name = $_POST['fullname'];
//}
//$message .= "Thanks for your input $unsafe_name !";
//echo $message;
if (isset($comment) && $comment == '') {
$bedrooms = $_POST['bedrooms'];
$bedrooms = clean_string($db_server, $year);
$comment = clean_string($db_server, $_POST['comment']);
}
else {
$query1 = "INSERT INTO comments (comment) VALUES ('$comment')";
$result = mysqli_query($db_server, $query1); if(!result){ die("Insert failed: " . mysqli_error($db_server));
}
$message = "Thanks for your comment";
}
function getPosts(mysqli $db_select){
$query1 = "SELECT * FROM comments";
$result1 = mysqli_query($db_server, $query1);
while($array = mysqli_fetch_array($result1)){
$comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="home.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<div id="middle">
<h2><strong>HELLO!</strong></h2>
<h2>Welcome to <strong>Cosy Cribs</strong> website!</h2>
<p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p>
<p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p>
<p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p>
<h2>ENJOY!</h2>
</div>
<form id="comments" action="home.php" method="post">
<select name="comments">
</select>
<h1>Do you have a comment on preferred company or number of bedrooms?</h1>
Comment: <textarea rows="2" cols="30" name="comment"></textarea>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Seems like you are overwriting your $db_server on the line that reads:
$db_server = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
So you should change that to be another variable like $result1:
$result1 = mysqli_query($db_server, $query1) or
die("Insert failed: " . mysqli_error($db_server));
That said, are you actually connecting via $db_server anywhere else in your code? Look out for errors similar to what I just pointed out.
your $db_server is null which should a valid mysqli instance. this indicates either database connection failed or you didn't initialize $db_server or you overwritten it and looks like last option is true.
$db_server = mysqli_query($db_server, $query1)
this overwrites $db_server.
Insted of $db_server use $db_select. This may work as your $db_server variable does not have a connection to database. Its just a connection to server.
when i upload file it show array file empty, however upload is on in my php.ini.
please see my code blow and let me know where is the error.
i have looked all around the web for solution but did not found, im using PHP Version 5.3.25 on centos 5.4 kernel version 2.6.18-164.el5.
thanks and regards
hadi
html page.
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
add_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(
file_get_contents($_FILES['uploaded_file']['tmp_name'])
);
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
} else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
} else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
} else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I'm new to PHP, and I tried to research this question but maybe I'm not asking right... I can tell from other posts/instructionals that I can not user header() or setcookie() after printing out HTML...
I commented out the header "redirects" - is there an alternative to this that I can put after HTML?
It's the setcookies that are failing at the moment:
what am I not seeing? I keep getting errors but my HTML is after the PHP:
if (!isset($_COOKIE["user"])) {
$sUserIdentity = $_POST["userIdentity"];
//username is not accepted as a get value
$sPassword = $_POST["password"];
$sEmail = $_POST["email"];
$cnn= odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
//check to see if email account or username already used
$sql2 = "select id from i_user where email = '" . $sEmail . "' or username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$id = odbc_result($result,"id");
if ($id == ''){
$cnnCreate = odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
$sqlCreate = "insert into i_user (username,email,salt,active) values ";
$sqlCreate .= "(";
$sqlCreate .= "'" . $sUserIdentity . "',";
$sqlCreate .= "'" . $sEmail . "',";
$rsCreate = odbc_exec($cnnCreate, $sqlCreate);
$sql2 = "select * from i_user where email = '" . $sEmail . "' and username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$expire=time()+60*60*24*30;
setcookie("uid", odbc_result($result,"id"), $expire);
setcookie("user", odbc_result($result,"username"), $expire);
if ($rsCreate){
$sMsg = "congratulations " . $_COOKIE["user"] . " and welcome ";
}
else {
$sMsg = "There was an error with the query";
}
}else{
$sMsg = "User " . $id . " already in DB";
//header('Location: ../fec/createuser.php?error=id');
}
}
//echo $sqlCreate;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Form</title>
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.2.custom.min.js"></script>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<style>
</style>
</head>
<body>
</body>
</html>
Make sure <?php is at the very beginning of the file, with no blank lines before it. And you can't print or echo anything before calling setcookie().
Why don't you use output buffering?
<?php
ob_start();
?>
<html>
<body>
...
</body>
</html>
<?php
ob_end_flush();
?>
This will put any output into a buffer and you can modify header information as long as the buffer isn't flushed.
This will also avoid problems in case a PHP warning or error message was sent to output before you write to the header.