I am learning to create my own database and so far I have "thanks to tutorials and stackoverflow" to create a register page.
Once registered, they enter username and password and it opens the upload page.
Its to upload house details
On the upload page they enter City: Price: Decription: Bedrooms: Bathrooms: Photo:
So far, once they input the data it displays on the index page, I have done pagination, re-sized the uploaded image, and all ok.
My next step is on the index page each entry for it to open to a new window displaying their data.
The thing is that makes it hard for me to find the code, is that I want the user to input a name for their details page when uploading the house details.
And for it not to end in .php or .html just www.mysite.com/the-desired-name
my code so far might be using bad code but it works fine, and its helping me achieve what I want till I have the experience to perfect it all.
my code is upload page
<form enctype="multipart/form-data" action="add.php" method="POST">
City: <input type="text" name="city"><br>
Price: <input type="text" name = "price"><br>
Decription: <input type="text" name ="description"><br>
Bedrooms: <input type="text" name="bed"><br>
Bathrooms: <input type="text" name="bath"><br>
Your desired link name MYSITE.COM/ <input type="text" name="link"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Add">
</form>
And then it uploads via
<?php
//This is the directory where images will be saved
$target = "upload/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$city=$_POST['city'];
$price=$_POST['price'];
$description=$_POST['description'];
$bed=$_POST['bed'];
$bath=$_POST['bath'];
$link=$_POST['link'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("host", "username", "password") or die(mysql_error()) ;
mysql_select_db("mydatabase") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$city', '$price', '$description', '$bed', '$bath', '$link', '$pic')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
require_once 'SimpleImage.php';
$image = new SimpleImage();
$image->load($target);
$image->resize(50,50);
$image->save($target);
//Tells you if its all ok
echo "<script>window.location = 'http://www.mysite.com'</script>";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
and then it displays on the index page
<?php
// Connects to your Database
mysql_connect("host", "username", "password") or die(mysql_error()) ;
mysql_select_db("mydatabase") or die(mysql_error()) ;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 2;
$data = mysql_query("SELECT * FROM employees ORDER BY bath ASC LIMIT $start_from, 2") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
?>
<?php
//Outputs the image and other data
echo "<img src=http://www.mysite.com/upload/".$info['photo'] . " /><br />";
echo "<b>City:</b> ".$info['city'] . " ";
echo "<b>Price:</b> ".$info['price'] . " ";
echo "<b>Bed:</b> ".$info['bed'] . " ";
echo "<b>Bath:</b> ".$info['bath'] . " ";
echo "<b>Extra:</b> ".$info['description'] . " ";
echo "<b>Link:</b> <u>www.mysite.com/</u> ".$info['link'] . " <br /><br /></a>";
}?>
<?php
$data = mysql_query("SELECT COUNT(photo) FROM employees") or die(mysql_error());
$info = mysql_fetch_row($data);
$total_records = $info[0];
$total_pages = ceil($total_records / 2);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
?>
for it not to end in .php or .html just www.mysite.com/the-desired-name
Assuming you are on Apache, have a look at mod_rewrite. You can use that to turn requests like the one you stated into internal requests to /showpage.php/the-desired-name. Inside that showpage.php script, you can access the-desired-name via the $_SERVER['PATH_INFO'] variable. Or, if that does not work, via some other variable which phpinfo() will tell you.
Related
I am reading "Head first PHP book" and stumbled at chapter 5 where file upload is implmented. I did it on XAMPP on windows 7. The path to the file is the following:
htdocs-->chapter5-->form.php
Here is my simplified version of the original code.
<html>
<head>
<title>Guitar Wars - Add Your High Score</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<head>
<body>
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
<hr />
<h2>Guitar Wars - Add Your High Score</h2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
</body>
The whole idea is the following. User enters his name and score and selects file for upload via self-submitting html form:
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
then the data is processed by php script in the same file:
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
When i try to submit the form for processig the message is
problem uploading
which suggests that move_uploaded file failed. What i did are the following:
Chagged permission of the entire htdocs folder - did not work.
Created image folder within the chapter5 directory and changed its permission it did not work. I.e. created directory image as
htdocs-->chapter5-->image
and changed permissions of the directory. then I called move_uploaded_file as
move_uploaded_file($_FILES['screenshot']['tmp_name'],
'/image/.$screenshot') or die("problem uploading");
this approach did not work
Created image directory in the htdocs directory and tried the following call
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
every time i have
probem uploading
text written on the page after form submission. I looked at file_upload record in the php.ini file everyhting seem fine:
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir="C:\xampp1\tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=2
I also changed the permmision of 'C:\xampp1\tmp'
Nothing worked. Can anybody suggest what am i doing wrong?
First things first, turn on error reporting so you can see the actual error/warning that is happening - How do I get PHP errors to display?
I ran your code and it works if the destination directory actually exists. One approach to ensuring that it exists is to create the directory on the fly.
Not sure if this is the right location for you, but using ./image/ will create the image in the directory where your script is executing. You can play around with $destinationDirectory until you get your desired location and it should continue to work.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
...
if (!empty($name) && !empty($score) && !empty($screenshot)) {
$destinationDirectory = './image/';
// Check if the destination is a directory. If not, create it.
if (!is_dir($destinationDirectory) && !mkdir($destinationDirectory)) {
die("Error creating folder $destinationDirectory");
}
$finalPath = $destinationDirectory . $screenshot;
if (!move_uploaded_file($_FILES['screenshot']['tmp_name'], $finalPath)) {
die("problem uploading");
}
...
'/image/.$screenshot' likely should be '/image/'.$screenshot
#waterloomatt, yes, this is just typo
You should edit your question with the real code then otherwise, it will throw people off.
And final note - $query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
This code is fully susceptiable to SQL injection because you're passing user supplied data directly to your database. Look into prepared statements - https://phpdelusions.net/pdo#prepared
The solution was pretty obvious. I created simple form.html file and separate form.php form handler. When 2 are separate then everything works fine. When the form is self-submitting it gave me error messages. Looks like this is related to form submission.
I have created a php script with a form that it should insert some data into database, it actually add the text and the ID but it does not add the file.
the database looks like this:
Database name: highmob_comenzi
table name: players
in table we got 3 rows:
ID (auto_increment)
name (the name that we insert from the form)
schite (where the files should be uploaded) Type: blob Colation: none , all none
this is the script what I have tried so far
<?php
include('connect-db.php');
?>
<?php
function renderForm($name, $schita, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="hidden" name="name" value="<?php echo $name; ?>"/>
<input type="file" id="schita" name="schita" >
<button type="submit" name="submit">Add Data</button>
</form>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$schita = mysql_real_escape_string(htmlspecialchars($_POST['schita']));
if ($name == '')
{
$error = 'Error !!';
renderForm($name, $schita, $error);
}
else
{
mysql_query("INSERT players SET name='$name', schita='$schita'")
or die(mysql_error());
header("Location: mobila.php");
}
}
else
{
renderForm('','','','','');
}
?>
This script creates a page for each ID when we insert data in the form
Like pagename.php?id=4
I want when i fill the form after he create the page when i open the page to see the uploaded file only on that page,
any idea why its not working?
Get the request file using $_FILES, also you need to confirm your mysql field (schita) is a blob type
You need to correct insert query. You are missing 'into' keyword. Change query to:
mysql_query("INSERT into players SET name='$name', schita='$schita'");
You need to convert image to base64 and then save it to Database.
// Select file type
$target_file = basename($_FILES["file"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['schita']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "INSERT into players(schita) values('".$image."')";
mysqli_query($con,$query);
I have managed to upload the file using this script
<?php
$dbh = new PDO("mysql:host=localhost;dbname=highmob_comenzi", "highmob", "PW");
if(isset($_POST['btns'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("UPDATE players SET data='$myfile', name='$name', mime='$type' WHERE id='$id'");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<!-- form -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/>
<button name="btns"> Incarca Schita </button>
</form>
<!-- display data -->
<?php
$stat = $dbh->prepare("select * from players");
$stat->execute();
while($row = $stat->fetch()){
echo "<a target='_blank' href='viewschita.php?id=".$row['id']."'>".$row['name']."</a>";
}
?>
The problem is i got no idea how to make a link to the file, any idea how?
Iam trying to create a private messaging system in which user sends message to another user and that content is inserted into database..Iam using a random number called hash to identify a conversation between two people..table for that is "message_group" and table for saving messages is "messages"..here comes the problem..
When I type something in text area and click on sendmessage button it inserts the data into the messages database..But if type something again and try to send it , the data wont enter into database..coz of this the other person is getting only first message..Please help me solving this problem..here's the code
<html>
<head>
<title>new convo</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'message_title_bar.php';?>
<?php include 'functions.php';?>
<div>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$my_id=$_SESSION['user_id'];
$user=$_GET['user'];
$random_number=rand();
$message=$_POST['message'];
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con=mysqli_query($connect,$query_string) or die(mysqli_error($connect));
if(mysqli_num_rows($check_con)==1){
echo "<p>Conversation already Started</p>";
}else{
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connect,"INSERT INTO message_group VALUES('$my_id' , '$user' , '$random_number')");
mysqli_query($connect,"INSERT INTO messages VALUES ('','$random_number','$my_id','$message')");
echo "<p>Conversation started</p>";
}
}
?>
Enter message:<br />
<textarea name='message' rows='7' cols='60'></textarea>
<br />
<br />
<input type='submit' name="submit" value="sendmessage" />
</form>
<?php
}
else{
echo "<b>Select User</b>";
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
$user_list=mysqli_query($connect,"SELECT `id`,`username` FROM `users`");
while($run_user=mysqli_fetch_array($user_list)){
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
Any help is appreciated.
<html><head><title>new convo</title></head><body>
<?php include 'connect.php'; ?>
<?php include 'message_title_bar.php'; ?>
<?php include 'functions.php'; ?>
<?php $connect = mysqli_connect('localhost', 'root', '', 'php_mysql_login_system'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); ?>
<div>
<?php
if (isset($_GET['user']) && !empty($_GET['user'])) {
?>
<form method='post'>
<?php
if (isset($_POST['message']) && !empty($_POST['message'])) {
$my_id = $_SESSION['user_id'];
$user = $_GET['user'];
$message = $_POST['message'];
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con = mysqli_query($connect, $query_string);
if (mysqli_num_rows($check_con)) {
$f_array = mysqli_fetch_array($check_con);
$hash = $f_array['hash'];
echo "<p>Conversation already Started</p>";
} else {
$hash = rand();
mysqli_query($connect, "INSERT INTO message_group VALUES('$my_id' , '$user' , '$hash')");
echo "<p>Conversation started</p>";
}
mysqli_query($connect, "INSERT INTO messages VALUES ('', '$hash', '$my_id', '$message')");
}
?>
<label for="message">Enter message:</label>
<textarea name='message' id="message" rows='7' cols='60'></textarea>
<br/>
<br/>
<input type='submit' name="submit" value="sendmessage"/>
</form>
<?php
} else {
echo "<b>Select User</b>";
$user_list = mysqli_query($connect, "SELECT `id`,`username` FROM `users`");
while ($run_user = mysqli_fetch_array($user_list)) {
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
There are many mistakes in code brother read basic first... and you are not using echo function to print old chat.
Just echo old chat. before post function.
steps:
1. Check if users already chatting.
2. If they are chatting echo chat which they already chatted.
3. If not chatting then start new chat.
4. if they are not chatting you dont need to echo anything just echo new message.
Your present code will just show you last message i think. because your page getting reload. and after it loads its just printing your last message in my view.. you need to print old chat as well.
On my website I've displayed a list of registered users on a members page using echo in PHP. I'd now like to link the names of these users to their profile pages. Is there a way to do this?
My current code:
<html>
<title>Find User Info</title>
<body>
<form method="POST">
<p>Type Username: </p><input type="text" name="username"placeholder="Enter Username...">
<br>
<input type="submit" name="submit" value="Search User">
</form>
<?php
session_start();
error_reporting(0);
$connection = mysql_connect("localhost", "root", "***"); // Establishing Connection with Server
$db = mysql_select_db("****", $connection); // Selecting Database from Server
$query = mysql_query("SELECT * FROM accs ORDER BY loginstatus"); //selecting all from table users where username is name that your is loged in
while($row = mysql_fetch_assoc($query))
{
echo $row['name'];
}
if(isset($_POST['submit'])){
$username = $_POST['username'];
$_SESSION['searchuser'] = $username; //setting session username to one from table, this is useful if you login, that restart your browser and than you go in url where is your profile.php... Anyway this is useful :D
header( 'Location: user.php' ) ;
}
?>
</body>
</html>
The template link is like: mywebsite.com/search/user.php
echo ''.$row['name'].'';
is this what you are looking for ?
All you'll have to do is echo out an <a> element with the appropriate parameters for the link.
In your loop where you echo out the name of the user. you can include the <a> element definitions and only have the name as the text of the link:
while($row = mysql_fetch_assoc($query)) {
$user_name = $row['name'];
$profile_link = "http://your-cool-site/users/" . $row['id'];
echo "<a href='" . $profile_link . "' >" . $user_name . "</a>";
}
This code assumes that the link to your user page is something like:
http://your-cool-site/users/USER_ID
Wondering if you can help?
I am currently working on a script that allows an admin to upload a file to the server. When the file uploads it takes information from the form and stores it in the database, to later allow users who have permissions to download it.
I have managed to make the form:
Select File To Upload
<div style="width:100%; margin:5px;">
<form action="uploadclientfile.php" method="post" enctype="multipart/form-data" name="upload" style="margin:5px;">
<label> File</label><br /><br />
<input name="uploaded_file" type="file" class="input-xlarge" required/>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /><br /><br />
<label>Select Users Who Can Download The File</label><br /><br />
<select name="users[]" multiple="multiple" style="width:300px">
<?php
$useruploadids = mysql_query("SELECT member_id, firstname, lastname FROM members");
while ($row = mysql_fetch_assoc($useruploadids)) {
$user_id = $row['userid'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
?>
<option value=""<?php echo $user_id ?>"><?php echo $firstname ?><?php echo $lastname ?></option>
<?php } ?>
<input name="Upload" type="submit" value="Upload" class="btn" />
</form>
So this will create a multiselect box with all users from the database to select more than one if required. It calls their userid first name and last name. But it doesn't display the user id. Which is fine.
The next file is the uploading file, the issue I am encountering is in the database. It isn't recording the userids selected and the filename is always coming up as array. Although it does save the file location correctly.
Any idea what is wrong?
<?php
$target = "clientfiles/";
$target = $target . basename( $_FILES['uploaded_file']['name']);
$userid=$_POST['users[]'];
$file=($_FILES['uploaded_file']);
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
mysql_query("INSERT INTO `cfiles` VALUES ('$userid', '$file', '$target')") ;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Any clues?
Thank you for reading
Given that your allowing the user to select multiple userids with the form notation [] the following $userid=$_POST['users[]']; will be an array. Given $userid is an array when you storing it as a string the value Array() will be stored instead of the actual user_id value. If you database table field user_id is of type INT then string value of Array() can't even be stored it will result in 0.
If you goal is to store multiple values, converting into multiple records you should iterate through the $user_id array and store them as follows
foreach ($userid as $id) {
mysql_query("INSERT INTO `cfiles` VALUES ('$id', '$file', '$target')")
}