I am trying to add more than one picture to the webpage but it only allows me to add 1. Im trying to add more than 3 images onto the webpage, All ive done is add a button that allows you to select the file but i want more that 1 files and minimum of 4 pictures to be uploaded
heres the code:
<section class="left">
<ul>
<li>Manufacturers</li>
<li>Bikes</li>
</ul>
</section>
<section class="right">
<?php
if (isset($_POST['submit'])) {
$stmt = $pdo->prepare('INSERT INTO bikes (model, description, price, manufacturerId)
VALUES (:model, :description, :price, :manufacturerId)');
$criteria = [
'model' => $_POST['model'],
'description' => $_POST['description'],
'price' => $_POST['price'],
'manufacturerId' => $_POST['manufacturerId']
];
$stmt->execute($criteria);
if ($_FILES['image']['error'] == 0) {
$fileName = $pdo->lastInsertId() . '.jpg';
move_uploaded_file($_FILES['image']['tmp_name'], '../images/bikes/' . $fileName);
}
echo 'Bike added';
}
else {
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
?>
<h2>Add Product</h2>
<form action="addbike.php" method="POST" enctype="multipart/form-data">
<label>Bike Model</label>
<input type="text" name="model" />
<label>Description</label>
<textarea name="description"></textarea>
<label>Condition</label>
<input type="text" name="Condition" />
<label>Price</label>
<input type="text" name="price" />
<label>Category</label>
<select name="manufacturerId">
<?php
$stmt = $pdo->prepare('SELECT * FROM manufacturers');
$stmt->execute();
foreach ($stmt as $row) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select>
<label>Bike image</label>
<input type="file" name="image" />
<input type="submit" name="submit" value="Add Product" />
</form>
<?php
}
else {
?>
<h2>Log in</h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="username" />
<label>Password</label>
<input type="password" name="password" />
<input type="submit" name="submit" value="Log In" />
</form>
<?php
}
}
?>
To allow multiple file selection from input file will be like
<input type="file" name="image" multiple>
To fetch all the files selected
print_r($_FILES); // will return you detail of all files in array
The multiple attribute of the input tag is not supported in Internet
Explorer 9 and earlier versions.
You can select multiple files at a time but you need to add multiple then you can select files like this.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
<input type="file" name="img[]" multiple>
<input type="submit">
</form>
</body>
</html>
<?php
echo '<pre>';
$img = $_FILES['img'];
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$newname = date('YmdHis',time()).mt_rand().'.jpg';
move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
}
}
function reArrayFiles($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}
Related
I have a little problem.
I'm making form that submits simple article to database and then displays it on admin.php page.
Everything works fine, except image.
First i upload it to my server and then I try to add string(path of this image) to database.
However I can't use variable $filepath in second if statement.
I can echo it after image upload but can't use in other if.
Could u help me?
Thanks in advance.
Here's code:
<?php session_start();
if (!isset($_SESSION['logged-in']))
{
header('Location: index.php');
exit();
}
?>
<?php
include('db_connect.php');
if(isset($_POST['btn_upload'])) {
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
move_uploaded_file($filetmp,$filepath);
$result = mysqli_query($mysqli, "INSERT INTO upload_img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')");
echo '<img src="' . $filepath . '" alt="">';
echo $filepath;
}
if ( isset($_POST['add']) ) {
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$image = strip_tags($filepath);
$statement = $mysqli->prepare("INSERT bikes (title,image,content) VALUES (?,?,?)");
$statement->bind_param("sss",$title,$image,$content);
$statement->execute();
$statement->close();
header('Location: admin.php');
}
?>
<form method="post" action="" class="ui form">
<div class="required field">
<label>Title</label>
<input type="text" name="title" id="title">
</div>
<div class="required field">
<label>Content</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
</div>
<div class="required field">
<label>Image</label>
<input type="text" name="image" id="image">
</div>
<input type="submit" class="ui primary button" id="add" name="add" value="Add article"></input>
</form>
<form action="addbike.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img" />
<input type="submit" name="btn_upload" value="Upload">
</form>
Since both of your forms work independently(with co-relation with each other whatsoever), $filepath variable won't be accessible in the second if block. However, what you can do is, merge both of your forms together so that all of your form's textual data and image would be accessible in a single submit button.
HTML:
<form method="post" action="" class="ui form" enctype="multipart/form-data">
<div class="required field">
<label>Title</label>
<input type="text" name="title" id="title">
</div>
<div class="required field">
<label>Content</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
</div>
<div class="required field">
<label>Image</label>
<input type="text" name="image" id="image">
</div>
<input type="file" name="file_img" />
<input type="submit" class="ui primary button" id="add" name="add" value="Add article"></input>
</form>
PHP:
if (isset($_POST['add']) && is_uploaded_file($_FILES["file_img"]["tmp_name"])) {
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
if(move_uploaded_file($filetmp, $filepath)){
$result = mysqli_query($mysqli, "INSERT INTO upload_img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')");
if($result){
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$image = strip_tags($filepath);
$statement = $mysqli->prepare("INSERT bikes (title,image,content) VALUES (?,?,?)");
$statement->bind_param("sss",$title,$image,$content);
$statement->execute();
$statement->close();
header('Location: admin.php');
exit();
}else{
// error handling
}
}else{
// error handling
}
}
btn_upload is mutually exclusive to add, so the if statement which executes for btn_upload doesn't also run for add.
If you want it to be a two-phase process (upload image, then add) then you have to set a hidden input whose value is the filepath.
However, ideally the user would fill in name and provide an image and then submit them together. In order to do that, place all inputs inside the same form element and remote the "Add" button.
We are using a switch statement to switch between languages but when we try to use case 1(the dutch/nl flag), the results no longer shows up. Everything works fine without using the switch case, however.
This is our index
<html>
<head>
<title>Welcome to Medispeak</title>
<link rel=stylesheet href=Medi.css>
</head>
<body>
<header>
<div class="lang">
<form method="GET" action="?set=lang">
<input id="vlag" name="lang" class="nl" type="submit" value="1">
<input id="vlag" name="lang" class="en" type="submit" value="2">
<input id="vlag" name="lang" class="du" type="submit" value="3">
<input id="vlag" name="lang" class="es" type="submit" value="4">
<input id="vlag" name="lang" class="pt" type="submit" value="5">
<input id="vlag" name="lang" class="fr" type="submit" value="6">
</form>
</div>
</header>
<h1>Zoeken op Medicijn</h1>
<form method="post" action="tabel.php" target="Mediframe">
Voer medicijn in:
<input type="text" name="zoek">
<br/>
<input type="submit" value="zoeken">
<input type="reset" value="wissen">
</form>
<div id="outer">
<div id="inner">
<iframe name="Mediframe" width="800" height="600" frameborder=0>
</iframe>
</div>
</div>
</body>
</html>
This is our search function:
<html>
<head>
<title>Medispeak</title>
<link rel=stylesheet href=ProjectCSS.css>
</head>
<body>
<?php
include 'db.php';
print_r($_REQUEST);
$zoek = $_REQUEST['zoek'];
$lang = $_REQUEST['lang'];
if ( empty ( $lang ) ) { $lang = "1"; }
switch ($lang) {
case "1":
echo 'case1';
try
{
$sQuery= "SELECT Medibijsluiter
FROM Medispeak
WHERE Medinaam LIKE ?";
$oStmt = $db->prepare($sQuery);
$oStmt->bindValue(1, "%$zoek%", PDO::PARAM_STR);
$oStmt->execute();
if($oStmt->rowCount()>0)
{
echo '<table border="2">';
echo '<thead>';
echo '<td>Medibijsluiter</td>';
echo '</thead>';
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>'.$aRow['Medibijsluiter'].'</td>';
echo '</tr>';
}
echo '</table>';
}
else
{
echo 'Helaas,geen gegevens bekend';
}
break;
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
$db = null;
?>
</body>
</html>
You should use $_GET['lang'] instead of $_POST['lang']. Or you can user $_REQUEST['zoek'] and $_REQUEST['lang'].
If you have form type as GET, then the form data can be accessed using $_GET or $_REQUEST. If the type is POST, you should use either $_POST or $_REQUEST.
Read this to know more about GET, POST and REQUEST in PHP
So change your code
$zoek = $_POST['zoek'];
switch ($_GET['lang']) {
or
$zoek = $_REQUEST['zoek'];
switch ($_REQUEST['lang']) {
Updated Code
<html>
<head>
<title>Welcome to Medispeak</title>
<link rel=stylesheet href=Medi.css>
</head>
<body>
<?php
if(!empty($_REQUEST['zoek'])) {
$zoek = $_REQUEST['zoek'];
include 'db.php';
$lang = $_REQUEST['lang'];
if ( empty ( $lang ) ) { $lang = "1"; }
switch ($lang) {
case "1":
echo 'case1';
try
{
$sQuery= "SELECT Medibijsluiter FROM Medispeak WHERE Medinaam LIKE ?";
$oStmt = $db->prepare($sQuery);
$oStmt->bindValue(1, "%$zoek%", PDO::PARAM_STR);
$oStmt->execute();
if($oStmt->rowCount()>0)
{
echo '<table border="2"><thead><td>Medibijsluiter</td></thead>';
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr><td>'.$aRow['Medibijsluiter'].'</td></tr>';
}
echo '</table>';
} else {
echo 'Helaas,geen gegevens bekend';
}
break;
}
catch(PDOException $e) {
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
}
$db = null;
}
?>
<header>
<div class="lang">
<form method="GET" action="?set=lang">
<input id="vlag" name="lang" class="nl" type="submit" value="1">
<input id="vlag" name="lang" class="en" type="submit" value="2">
<input id="vlag" name="lang" class="du" type="submit" value="3">
<input id="vlag" name="lang" class="es" type="submit" value="4">
<input id="vlag" name="lang" class="pt" type="submit" value="5">
<input id="vlag" name="lang" class="fr" type="submit" value="6">
</form>
</div>
</header>
<h1>Zoeken op Medicijn</h1>
<form method="post" action="" target="Mediframe">
Voer medicijn in:
<input type="text" name="zoek">
<br/>
<input type="submit" value="zoeken">
<input type="reset" value="wissen">
</form>
<div id="outer">
<div id="inner">
<iframe name="Mediframe" width="800" height="600" frameborder=0>
</iframe>
</div>
</div>
</body>
</html>
Update this code in index file. tabel.php content also added in this
file. So the form will be submitted to the same page and it will not
refer tabel.php.
You're using two different forms, one for language selection and one for searching. Thus, when submitting the second form whatever you selected in the first one gets completely ignored. (Additionally, the first form is using $_GET, and you're looking for the language in $_POST)
A quick fix would be moving your language selection element into the second form, so the selected language gets send along with the search phrase.
change switch ($_POST['lang']) to switch ($_GET['lang']) you mix up POST and GET with your two forms
<html>
<head>
<title>Welcome to Medispeak</title>
<link rel=stylesheet href=Medi.css>
</head>
<body>
<header>
<div class="lang">
<form method="GET" action="?set=lang">
<input id="vlag" name="lang" class="nl" type="submit" value="1">
<input id="vlag" name="lang" class="en" type="submit" value="2">
<input id="vlag" name="lang" class="du" type="submit" value="3">
<input id="vlag" name="lang" class="es" type="submit" value="4">
<input id="vlag" name="lang" class="pt" type="submit" value="5">
<input id="vlag" name="lang" class="fr" type="submit" value="6">
</form>
</div>
</header>
<form method="post" action="tabel.php" target="Mediframe">
<h1>Zoeken op Medicijn</h1>
Voer medicijn in:
<input type="text" name="zoek">
<br/>
<input type="submit" value="zoeken">
<input type="reset" value="wissen">
<input id="vlag" type="hidden" name="lang" class="nl" value="<?=$_GET["lang"]?>">
</form>
<div id="outer">
<div id="inner">
<iframe name="Mediframe" width="800" height="600" frameborder=0>
</iframe>
</div>
</div>
</body>
</html>
tabel.php
<html>
<head>
<title>Medispeak</title>
<link rel=stylesheet href=ProjectCSS.css>
</head>
$zoek = $_POST['zoek'];
switch ($_POST['lang']) {
case "1":
try {
$sQuery = "SELECT Medibijsluiter
FROM Medispeak
WHERE Medinaam LIKE ?";
$oStmt = $db->prepare($sQuery);
$oStmt->bindValue(1, "%$zoek%", PDO::PARAM_STR);
$oStmt->execute();
if ($oStmt->rowCount() > 0) {
echo '<table border="2">';
echo '<thead>';
echo '<td>Medibijsluiter</td>';
echo '</thead>';
while ($aRow = $oStmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td>' . $aRow['Medibijsluiter'] . '</td>';
echo '</tr>';
}
echo '</table>';
} else {
echo 'Helaas,geen gegevens bekend';
}
} catch
(PDOException $e) {
$sMsg = '<p>
Regelnummer: ' . $e->getLine() . '<br />
Bestand: ' . $e->getFile() . '<br />
Foutmelding: ' . $e->getMessage() . '
</p>';
trigger_error($sMsg);
}
$db = null;
break;
}
?>
</body>
</html>
But you can do it more cleaner. you should use a select imput within your second form :)
i'm trying to make CMS with PHP
i need to get the if from post request
<form action="updatevideo.php" method="post" role="form">
Title: <input name="title" type="text" required> <br />
description:<input name="desc" type="text" required> <br />
url: <input name="ytl" type="text" required> <br />
<input type="hidden" name="id" />
<input type="submit" name="addVideo" value="Add New Video" />
</form>
how can i make this input's value = id
<input type="hidden" name="id" />
on control page
public function Update()
{
/*
1-get data into variables
2-validation
3-Database
*/
if(isset($_GET['id']) && (int)$_GET['id']>0)
{
$id = (int)$_GET['id'];
$user = $this->videoModel->Get_By_Id($id);
print_r($user);
echo
'
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="updatevideo.php" method="post" role="form">
Title: <input name="title" type="text" required> <br />
description:<input name="desc" type="text" required> <br />
url: <input name="ytl" type="text" required> <br />
<input type="hidden" name="id" />
<input type="submit" name="addVideo" value="Add New Video" />
</form>
</body>
</html>
';
}
else
{
if(isset($_POST['addVideo']))
{
$id = $_POST['id'];
echo "5ara" ;
$title = $_POST['title'];
$desc = $_POST['desc'];
$url = $_POST['ytl'];
//Validation
$vid = $this->getVid($url); //video id -_-
$data = array(
'title' => $title,
'desc' => $desc,
'vid' => $vid
);
if($this->videoModel->Update($id,$data))
{
System::Get('tpl')->assign('message','User Updated');
System::Get('tpl')->draw('success');
}
else
{
System::Get('tpl')->assign('message','Error Updating User');
System::Get('tpl')->draw('error');
}
}
else
{
System::Get('tpl')->assign('message','NO USER CHOSEN');
System::Get('tpl')->draw('error');
}
}
}
Quite simple really. As you checked it exists and moved it into a variable you can just echo the $id into the value attribute of that input tag.
<input type="hidden" name="id" value="' . $id . '" />
Using your code:
echo '
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="updatevideo.php" method="post" role="form">
Title: <input name="title" type="text" required> <br />
description:<input name="desc" type="text" required> <br />
url: <input name="ytl" type="text" required> <br />
<input type="hidden" name="id" value="' . $id . '" />
<input type="submit" name="addVideo" value="Add New Video" />
</form>
</body>
</html>';
Define the VALUE attribute :
<input type="hidden" name="id" value="ID_VALUE"/>
OR if you have id in varible than use below code :
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
OR
As you are using the HTML in PHP than:
<input type="hidden" name="id" value="'.$id.'"/>
ID_Value should be your id like 1,2,3..etc.
And Get the id on Action page :
$id = $_POST['id'];
Apart from this you have mention POST in form method and on your
action page you are trying to get the values using GET method,
which is wrong.
Edited due to question edit.
<input type="hidden" name="id" value="'.$id.'" />
You echo a big block of text, this way you can concatenate the $id by stopping block output, including $id and resuming block output.
I designed a car selling website.
I have a form where certain information about cars is entered, it then is added to the database and displayed on my main form. How can I get the image to be sent to the server and then use a url as a source to the image.
Cheers.
Here is my code.
PHP:
<?php
try {
# Connect to SQLite database
$dbh = new PDO("sqlite:../Car_Sales_Network");
$make = $_POST['Make'];
$model = $_POST['Model'];
$badge = $_POST['Badge'];
$price = $_POST['Price'];
$trans = $_POST['Transmission'];
$ppl = $_POST['P_Plate_Legal'];
print_r($_POST);
$sth = $dbh->prepare('INSERT INTO Cars_On_Network
("car_make","car_model","car_badge","price","trans","P_Plate_Legal")
VALUES
(?, ?, ?, ?, ?, ?)');
$sth->execute(array($make, $model, $badge, $price, $trans, $ppl));
header("Location: ../Carsales_Network.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
HTML:
<!DOCTYPE html>
<html>
<head>
<title>New Vehicle</title>
<link type="text/css" rel="stylesheet" href="New_Car_Form.css"/>
</head>
<body>
<div id="main">
<form action="Insert_Car.php" method="post" enctype="multipart/form-data">
Make:<br>
<input type="text" name="Make">
<br>
Model:<br>
<input type="text" name="Model">
<br><br>
Badge:<br>
<input type="text" name="Badge">
<br>
Price:<br>
<input type="text" name="Price">
<br>
Transmission: <br>
<input type="radio" name="Transmission" value="Manual" checked>Manual
<br>
<input type="radio" name="Transmission" value="Auto">Automatic
<br><br>
<form enctype="multipart/form-data" action="upload_file.php" method="post">
P Plate Legal: <br>
<select name="P_Plate_Legal">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<br>
<br>
<input class="submit" type="submit" value="Submit">
<br>
Let's go back!
<br>
</div>
</body>
</html>
</body>
</html>
How can I post the uploaded image to the database to be used, I have a folder on my database full of the cars photos.
to upload files to server in php, use php fileupload function
move_uploaded_file ( string $filename , string $destination )
example:
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["fileToUpload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["fileToUpload"]["tmp_name"][$key];
$name = $_FILES["fileToUpload"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
for reference check move_uploaded_file()
I want to count set file upload. Here is my using code. Are there any better method to do this. Thanks.
<form action="index.php" method="post" enctype="multipart/form-data">
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<button name="submit" type="submit">Upload</button>
</form>
<?php
$img_error = '0';
$fill_img_count = '0';
if(isset($_POST['submit']))
{
$img_count = count($_FILES['new_image']);
echo "Total : ".$img_count."<br>";
for ($i=0 ; $i<=$img_count ; $i++)
{
if (isset($_FILES['new_image']) && !empty($_FILES['new_image']['name'][$i]))
{
$fill_img_count++;
}
}
echo "Set : ".$fill_img_count."<br>";
}
?>
$count_files = 0;
foreach ($_FILES['picture']['error'] as $item) {
if ($item != 4) {
$count_files++;
}
}
echo $count_files;
I'd recommend testing each ['error'] key against UPLOAD_ERR_OK.
You don't require to have name="new_image[]" as the name ... just new_image will suffice. If you post 1 or many, on the PHP side, you'll see $_FILES[]
Some useful links for you:
http://php.net/manual/en/reserved.variables.files.php
http://www.php.net/manual/en/features.file-upload.php
Some code:
if (empty($_FILES)) { echo "0 files uploaded"; }
else { echo count($_FILES) . " files uploaded"; }
Edit based on comment:
How to handle multiple file upload using PHP
From that post:
echo count($_FILES['file']['tmp_name']);
<?php
$count = 0;
foreach($_FILES['new_image']['error'] as $status){
if($status === UPLOAD_ERR_OK) {
$count++;
}
}
var_dump($count);
?>
<form action="test.php" method="post" enctype="multipart/form-data">
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<input name="new_image[]" type="file" />
<button name="submit" type="submit">Upload</button>
</form>