I have two PHP documents. One that connects to my MySQL server and database (it will also create the database if it doesn't exist). This document is titled "db_connect.php". My next PHP document is titled "create.php" and it is designed to connect to a specific table within the database and create that table if it doesn't exist. There's also a javascript document involved in this which makes it so the user can type things and enter them into the table without the page being refreshed. I don't think you'll need this document and so I won't include it, but I thought you guys might find it helpful to know that this is for a message board.
Here's my db_connect.php file:
<?php
$db = "my_db";
//establish a connection with the server
$connection = mysqli_connect('localhost', 'root', 'password');
if(!$connection){
exit("<p>Could not establish a connection :" . mysqli_connect_error() . "</p>");
}
//connect to the database
$dbSelect = mysqli_select_db($connection, $db);
if(!$dbSelect){
// Create database
$sql="CREATE DATABASE " . $db;
if (mysqli_query($connection, $sql)) {
} else {
echo "<p>Error creating database: " . mysqli_error($connection) . "</p>";
}
}
?>
Here's my create.php file:
<?php
//connect to the database
include('db_connect.php');
$table = 'NDI';
//update the table if the notes are posted
if(isset($_POST['notes'])){
$notes=$_POST['notes'];
$name=$_POST['name'];
$file = $_POST['file'];
$file2 = $_FILES['file'];
echo "<p>Hello $file $file2</p>";
/////////////////////////////////////////////
//Check for file type
/////////////////////////////////////////////
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "application/x-shockwave-flash")
)
&& ($_FILES["file"]["size"] < 999000)){
/////////////////////////////////////////////
//Check for errors
/////////////////////////////////////////////
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}else{
///////////////////////////////////////////
//Set the upload
///////////////////////////////////////////
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
/////////////////////////////////////////////////////////
//Check to see if file exists already
/////////////////////////////////////////////////////////
if (file_exists("../uploads/" . $_FILES["file"]["name"])){
//echo $_FILES["file"]["name"] . " already exists. ";
$_FILES["file"]["name"] = rand(1, 1000).$_FILES["file"]["name"];
}
////////////////////////////////////////////////////////////
//If not, move to the upload folder
////////////////////////////////////////////////////////////
$path = '../uploads/';
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$fn = basename( $_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $path.$fn);
//move_uploaded_file($_FILES["file"]["tmp_name"],
//"../uploads/" . $_FILES["file"]["name"]);
echo "Stored in: ../uploads/". $_FILES["file"]["name"];
$myImg = "../uploads/" . $_FILES['file']['name'];
//echo "\n $myImg";
}
//echo "<a href=../uploader/>Back</a>";
}else{
echo "Invalid file";
//echo $_FILES["file"]["type"];
}
if(!$myImg){
$myImg="../uploads/blank.png";
}
if(!$name){
$name="anonymous";
}
$sql= "INSERT INTO `$table` SET `name` = '$name', `notes`='$notes', `img`='$myImg'";
if (mysqli_query($sql)) {
echo '<p>Entry added</p>';
echo '<p>' . $title . ' Home </p>';
} else {
echo '<p>Error adding page: ' . mysqli_error() . '</p>';
}
}
//display results
$choices = mysqli_query("select * from " . $table);
if(!$choices){
// Create table
$sqlc="CREATE TABLE $table(`id` INT(5) AUTO_INCREMENT, `img` VARCHAR(50), `name` VARCHAR(25), `notes` TEXT(500), PRIMARY KEY (`id`))";
// Execute query
if (mysqli_query($connection, /*$db,*/ $sqlc)) {
} else {
echo "Error creating table: " . mysqli_error($connection/*, $db*/);
}
}
while($row = mysqli_fetch_array($choices)){
$img=$row['img'];
$note=$row['notes'];
$name=$row['name'];
echo "<p class='note'><img src='$img'><span class='name'>$name: </span>$note</p>";
}
?>
The problem I'm running into is that the page echos the error: "Error creating table: Table 'NDI' already exists" so my if statement if(!$choices) is returning true. This if statement is supposed to return false when the table already exists. I can't figure out what's wrong with it. Any feedback you guys could give would be greatly appreciated.
I would recommend using the PHP function mysqli_num_rows($choices) and changing if statement to:
if(mysqli_num_rows($choices) == 0) {
If you print_r the $choices variable as it is currently written, you will probably see that it is not empty. There was no error... There just were no rows returned. What you want to know is not if there was an error, but if there were any rows returned.
You were missing your $connection as the 1st parameter of mysqli_query -> $choices = mysqli_query("select * from " . $table);.
It should be -
//display results
$choices = mysqli_query($connection, "select * from " . $table);
if(!$choices){
...
}
You want to keep ! in if(!$choices) as now you are properly checking if your query failed/returned 0 rows, as mysql table $table does not exist.
Related
I have a jpg image stored in MySql Database table in the column with the data type as BLOB that part of the php code works fine.
I am trying to display that image using the below php code but it would not work. I see a small icon on the screen which is definitely not the image ? what's wrong any help?
1) Read the image php file
<?php
header("Content-Type: image/jpg");
$db=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($db,"deal_bank");
$sql = "SELECT * FROM image";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpg;base64,'.base64_encode( $result['image'] ).'"/>';
?>
2) Upload the file into the MySql Database
<?php
$con=mysqli_connect("localhost","root","root123","deal_bank","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"deal_bank");
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] > 20000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$stmt = $con->prepare('INSERT INTO image (image) VALUES (?)');
$null = null;
$stmt->bind_param('b', $null);
$stmt->send_long_data(0, file_get_contents($_FILES['file']['tmp_name']));
$stmt->execute();
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// $image = addslashes(file_get_contents($_FILE['file']['tmp_name']));
//mysqli_query($con,"INSERT INTO image (image) VALUES ('{$image}') ");
}
}
} else {
echo "Invalid file";
}
?>
I replaced
header("Content-Type: image/jpg");
with
ob_start( );
it now works fine i am not sure what was the problem before ?
I've created an image upload using PHP, the idea being that the image will save to a directory and the path to the the database which is pretty standard. The problem is it wont save anything over 20kb. I have increased the max upload and post max size in the php.ini file to 10M and have also set size to < 200000kb in the function but it makes no difference. Can somebody please tell me where i have been banging my head off this for days now :(
File upload function (based on example at W3Schools)
function upload_file(){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["page_main_image"]["name"]);
$extension = end($temp);
if ((($_FILES["page_main_image"]["type"] == "image/gif")
|| ($_FILES["page_main_image"]["type"] == "image/jpeg")
|| ($_FILES["page_main_image"]["type"] == "image/jpg")
|| ($_FILES["page_main_image"]["type"] == "image/pjpeg")
|| ($_FILES["page_main_image"]["type"] == "image/x-png")
|| ($_FILES["page_main_image"]["type"] == "image/png"))
&& ($_FILES["page_main_image"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["page_main_image"]["error"] > 0) {
echo "Return Code: " . $_FILES["page_main_image"]["error"] . "<br />";;
}
else {
echo "Upload: " . $_FILES["page_main_image"]["name"] . "<br />";
echo "Type: " . $_FILES["page_main_image"]["type"] . "<br />";
echo "Size: " . ($_FILES["page_main_image"]["size"] / 1024) . " kb<br />";
if (file_exists("uploads/" . $_FILES["page_main_image"]["name"]))
{
echo $_FILES["page_main_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["page_main_image"]["tmp_name"],
"uploads/" . $_FILES["page_main_image"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["page_main_image"]["name"] . "<br />";
$image="{$_FILES['page_main_image']['name']}";
}
}
}
else {
echo "Invalid file";
}
return $image;
}
The form processing is as follows:
<?php
if (isset($_POST['submit'])) {
//Process the form
$image = upload_file();
$project_id = $_POST['project_id'];
//var_dump ($project_id);
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
//$image = $_POST["page_main_image"];
$page_bg_color = $_POST ["page_bg_color"];
$query = "INSERT INTO wireframes (";
$query .= " project_id, wireframe_title, browser_title, url_key, wireframe_type, page_main_image, page_bg_color";
$query .= " ) VALUES (";
$query .= " '{$project_id}','{$wireframe_title}', '{$browser_title}', '{$url_key}', '{$wireframe_type}', '{$image}', '{$page_bg_color}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("wireframes.php?id=$project_id");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_edit_wireframe.php?id= echo $_GET[$project_id]");
}
?>
The size in $_FILES is expressed in bytes. 200.000 = around 195 kilobyte.
Did you tested it without that condition in the if statement?
I'm currently trying to create a gallery upload page that allows users to select a album along with the album id being the value in the dropdown menu. On selecting their chosen album, the image is then uploaded and the data such as the image URL, ID, date and album added to a table. I've managed to get up to the stage of adding the album ID to my table although I'm having trouble with posting the value defined by the user in the dropdown menu.
I receive this error upon uploading an image:
Could not run query: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '[album]' at line 1
Any help would be much appreciated as MySQL isn't really an area I'm knowledgeable in, thanks :)!
My form :
<form action="assets/includes/upload.php" method="post" enctype="multipart/form-data">
<select name="album">
<? uploadList(); ?>
</select><br>
<input type="file" name="file" id="file" style="margin-top:37px; margin-left: 3px;"><br>
<input type="submit" name="submit" value="Submit" class="btn btn-primary" style="margin-left: 57px;">
</form>
The function carried out on the upload.php page:
function imageUpload() {
$id = ('$_POST[album]'); /////////// Focus being on this section ///////////
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
if (!$query2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("../../images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$file = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"],
"../../images/" . $_FILES["file"]["name"]);
$sql="INSERT INTO images (url, gallery)
VALUES
('$file','$id')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
}
}
else
{
echo "Invalid file";
}
}
In the second line of your PHP you have $id = ('$_POST[album]');. What's happening here is just "filling" $id with the literal string '$_POST[album]'. You need to change it so it becomes:
$id = intval($_POST['album']);
Now you're reading the value of album from the global $_POST array.
Please note that your code is vulnerable to SQL Injection, please take the appropriate measures to mitigate it. I added intval() for you as a basic protection while you read more about the subject.
I'm trying to create a gallery system which creates entries per image in a table allowing the script to retrieve all images with certain values. At the moment I've managed to get the file upload to work although it's not inputting the file name and gallery id into my table - it's not creating a row at all. Below is the code, any help would be amazing :)! I've messed around with a few things although file uploads and the likes aren't really my forte.
<?php
require "common.php";
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$id = $_GET['id'];
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
if (!$query2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("../galleries/images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../galleries/images/" . $_FILES["file"]["name"]);
$file = '["file"]["name"]';
$sql="INSERT INTO images (url, gallery)
VALUES
('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]);
die("Redirecting to: admin.php");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}
}
}
else
{
echo "Invalid file";
}
?>
The problem is that you redirect and kill your script before you execute your query:
$sql="INSERT INTO images (url, gallery)
VALUES
('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]);
die("Redirecting to: admin.php");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ nothing after this gets executed
if (!mysql_query($sql,$con))
^^^^^^^^^^^^^^^^^^^^^^ this query will never run
...
And you really should switch to PDO (or mysqli) and prepared statements to avoid sql injection problems.
I am trying to combined these two script (a file upload) and (a mysql update) so that the image file is both uploaded to the correct folder and the file path is then updated in the mysql database. I know the $sql update query is wrong and thats where my trouble is. Any help would be great.
//db connection
require "connect.db.php";
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
// update data in mysql database
$sql="UPDATE `characters` SET ch_image='/upload/$_FILES["file"]["name"]' WHERE ID='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='test.html'>View result</a>";
touch('../file.html');
clearstatcache();
}
else {
echo "Whoops: " . mysql_error(); ;
}
mysql_close();
?>
change $sql to this
$sql="UPDATE `characters` SET ch_image='/upload/" . $_FILES['file']['name'] . "' WHERE ID='$id'";