upload file to sql sever with php - php

I try to upload file to a database by using php.
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/$UploadName");
$url = "http://localhost/uploadandview/uploaded/$UploadName";
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}}?>
But i have a proplem, I can't upload any file mp3/mp4, just only upload file text, such as .doc,pdf, css, etc...
Please help me!

Try this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/".$UploadName);
$url = "http://localhost/uploadandview/uploaded/".$UploadName;
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}} ?>

Related

Issue in uploading images to MySQL database using PHP

I have this php code to upload image to the database, I have issue
with it and I don't know what is it, the database table name is
images and the fields are id, name VARCHAR(), photo LONGBLOB.
<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
</br>
</br>
</br>
<input type="submit" name="go" value="Upload"/>
</form>
<?php
if(isset($_POST['go'])){
if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
echo "Select a photo please";
}else {
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
save_image($image , $name);
}
}
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$conn = new mysqli($servername, $username, $password);
$qry = "insert into images (photo , name) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
?>
</body>
</html>
The result is as shown in the attached screenshot:
Result
Your function neglects to mention the database - you need to supply that as one of the parameters, like:
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database='xxxxxxxx';/* enter correct db name */
$conn = new mysqli( $servername, $username, $password, $database );
$qry = "insert into images (`photo`, `name`) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
FYI that said your code is vulnerable to sql injection - better to use prepared statements!
You're not using database name in the mysqli constructor. It should be like the following:
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);
Hope it should work now.

php/mysql connection on different servers

I have a local and a remote server on which I am developing a project
//local
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
//remote
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
At the moment I am commenting out the //local or //remote bit depending which way I am connecting. Of course, I regularly overwrite the connection file by mistake which is a pain.
Is there some sort of way I can detect which server I am on, and then connect automatically. I have tried googling but couldn't turn anything up maybe because i couldn't think of the right search terms.
Thanks
You can try this code:-
<?php
if ($_SERVER['SERVER_NAME'] == "localhost") {
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
}
elseif ($_SERVER['SERVER_NAME'] == "google.com") {
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
}
else {
echo "No configuration found!";
exit;
}
There are more than a few ways of doing this but one you could try is to detect which server you are on from the IP Address
if ($_SERVER['SERVER_ADDR'] === '127.0.0.1') {
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
} else {
//remote
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
}
try this code :-
$conn = new mysqli($servername1, $username1, $password1);
if (! $conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2);
}
Or check :-
$_SERVER['HTTP_HOST']=="localhost"

PHP Insert Query Using Prepare Statement

I have created an insert form. I'm doing an insertion operation into MySQL using prepare statement but it's not working. I don't understand what's wrong. Please help me to solve this issue. Is this what I did correct?
insert.php
<?php
include('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$sql = "Insert into main(client,category,sd,fd) values(:client,:category,:sd,:fd)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':client',$_POST['client'],PDO::PARAM_STR);
$stmt->bindParam(':category',$_POST['category'],PDO::PARAM_STR);
$stmt->bindParam(':sd',$_POST['sd'],PDO::PARAM_STR);
$stmt->bindParam(':fd',$_POST['fd'],PDO::PARAM_STR);
$stmt->execute();
?>
dbconn.php
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$mysqli = new mysqli($host,$user,$pwd,$db);
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
echo "Failed to connect to mysql : " . mysqli_connect_error();
exit();
}
?>
Its always good to put up the errors you are having.
You are using two different database connection types pdo, and mysqli. You only need one.
I stripped your code down to the minimum.
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
//$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
// make sure client and sd are set here
$stmt = $pdo->prepare("
INSERT INTO
main
(client,category,sd,fd)
VALUES
(:client,:category,:sd,:fd)
");
$success = $stmt->execute([
'client' => $client,
'category' => $category,
'sd' => $sd,
'fd' => $fd
]);

new mysqli_connect cat find database

<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "mineforums";
$connect = mysqli_connect($host, $username, $password, $db) or die(mysqli_error($connect));
?>
That is my php code to connect to my database. Whenever I try to just connect though it doesnt do anything. The way I have my login-form setup is the action will be to this code and then doesnt do anything and when I return to my index it says database not selected because if you're logged in it says 'Welcome, {username}'
you could split the process
<?PHP
$host = "localhost";
$username = "root";
$password = "";
$db = "mineforums";
$connect = mysql_connect($host, $username, $password)OR DIE("Could Not Connect To Server". MySQL_Error());
if($connect) {
mysql_select_db($db)OR DIE("Could Not Select Databse". MySQL_Error();
}
?>

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories