First of all i am beginner to php. here is the table structure of table "post"
<form method="post" action="postStatus.php">
<textarea rows="3" name="con" id="con" placeholder="what do you think?"></textarea><br>
<input type="file" accept="image/*" name="img" id="img>
<button name="post" id="post"> Post > </button>
</form>
postStatus.php
<?php
session_start();
require_once '../log/class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('../log/index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userid = $row['userID'];
$postid = microtime();
$con = $_POST['con'];
($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "root", ""));
mysqli_select_db($GLOBALS["___mysqli_ston"], vaistra);
if(isset($_POST['post']))
{
mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO post (`postId`, `userId`, `content`, `timeStamp`) VALUES ('$postid', '$userid', '$con', CURRENT_TIMESTAMP);");
}
header('Location: user_wall.php');
?>
i have to insert submit data to this table using this form. one input field for content column and file upload file upload in directory and path must be stored in database according to file type. like if uploaded file is a video then path must be stored in video column. postId and userId field is auto generated .
thanks in advance.
Related
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?
This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";
My problem is, when I upload a picture to a database, the upload is successful but the picture isn’t displayed. This is my code:
SQL file:
CREATE TABLE `images` (`id` int(11) NOT NULL auto_increment,`name` varchar(100) default NULL,`size` int(11) default NULL,`type` varchar(20) default NULL,`content` mediumblob,PRIMARY KEY (`id`)) ENGINE=MyISAM;
Index.php
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Image Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="150px">
<strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'><br>
</div>
<hr>
<? endif; ?>
<form action="index.php" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload"><br>
</div>
</form>
</tr>';}mysql_close();?>
image.php
<?php
// verify request id.
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo 'A valid image file id is required to display the image file.';
exit;
}
$imageId = $_GET['id'];
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'username', 'pass', 'db_name')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "SELECT type, content FROM images where id = {$imageId}";
if ($rs = mysqli_query($conn, $sql)) {
$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
mysqli_free_result($rs);
} else {
echo "Error: Could not get data from mysql database. Please try again.";
}
//close mysqli connection
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
if (!empty($imageData)) {
// show the image.
header("Content-type: {$imageData['type']}");
echo $imageData['content'];
} ?>
getImage.php
<?php
$id = $_GET['id'];
$link = mysql_connect("localhost", "username", "pass");
mysql_select_db("db_name");
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>
This code worked. I think the SQL database is incorrect or has problems to display images.
In order to display the image, you should use AJAX from JavaScript.
Since I added the function to upload a image my script doesn't work anymore .. That means I can't insert new posts into the datbase.
Please help me with this issue, thanks! For more questions just use the comments section below :)
PHP:
<?php
session_start();
header('content-type: text/html; charset=utf-8');
$uname = $_POST['username'];
$typ = $_POST['typ'];
$titel = $_POST['titel'];
$content = $_POST['content'];
$timestamp = time();
$db = new mysqli("localhost", "...", "...", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
// Verweis auf Bild
$image = $_FILES['image']['tmp_name'];
// Vorbereiten für den Upload in DB
$data = addslashes(file_get_contents($image));
// Metadaten auslesen
$meta = getimagesize($image);
$mime = $meta['mime'];
}
//create a prepared statement
$stmt = $db->set_charset("utf8");
$stmt = $db->prepare("INSERT INTO artikel (`red`, `typ`, `titel`, `content`, `image`, `mimetype`, `timestamp`) VALUES (?,?,?,?,?,?,?)");
//bind the username and message
$stmt->bind_param('sssssss', $uname, $typ, $titel, $content, $data, $mime, $timestamp);
//run the query to insert the row
$stmt->execute();
header("Location: erfolg.php");
?>
html form:
<form name="form2" action="insert.php" method="post">
Username:<br>
<input style="width:100%;" type="text" accept-charset="utf-8" name="username" value="<?php echo $_SESSION['username']; ?>" class="login_form" readonly><br><br>
Typ:<br>
<input style="width:100%;" type="text" name="typ" value="blog" class="login_form" readonly><br><br>
Titel:<br>
<input style="width:100%;" type="text" placeholder="Überschrift, z.B. Die Kunst des Spickens" name="titel"><br><br>
Inhalt:<br>
<textarea style="width:100%; height:250px; font:Arial, Helvetica, sans-serif !important;" type="text" placeholder="Inhalt" name="content"></textarea><br><br>
Bild anhängen (maximal 1 Bild):<br>
<input name="image" type="file"><br><br>
<input type="submit" value="Eintragen">
</form>
So, this was the php and html, thanks for your help!
And sorry for the bad english
First of all, your form needs enctype="multipart/form-data" to upload files.
Second, wouldn't it be an idea to move the uploaded file from the temp dir and save the path in the database, instead of saving the complete binary data of the temporary image?
http://php.net/manual/en/function.move-uploaded-file.php
Apologies for the newbie question, I just started with PHP, trying to fetch data when the user writes ID, and get info from database and write it into innerhtml of div's inside the form. How can I do it? thanks.
<form action="read.php" method="post">
Bring Data of ID <input type="text" name="id" />
<br/>
<input type="submit" />
<br/>
<div id="username" style="font-weight:bold;" /></div>
<br/>
<div id="email" style="font-weight:bold;" /></div>
<br/>
<div id="password" style="font-weight:bold;" /></div>
</form>
<?php
$db_username = "root";
$db_password = "";
$con = new PDO('mysql:host=localhost;dbname=test', $db_username, $db_password);
if (!$con) {
echo "error";
}
else {
echo "connected";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
}
else {
die("Die hacker!");
}
In your read.html, append your html code at the end:
<?php
[...]
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
$result = $sth->fetchAll();
}
else {
die("Die hacker!"); // seriously?
}
?><html><body><?php
print_r($result); ?>
</body></html>
This will print you the result of your query.
You can also iterate over the result, but i think you should really just read the documentation on PDO and how to use it. Maybe a simple introduction to PHP as well. This is a VERY basic Question.