I have an old mysql code where it successfully inserts the name of an image file into the database. But since old mysql is being decapitated, I have attempted doing the same in mysqli (can't use PDO because of version of PHP I have). The problem is that I cannot get the image file name to be inserted into the database in mysqli. What am I doing wrong?
Below is the mysqli code:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if(getimagesize($_FILES['fileImage']['tmp_name'])){
if( is_file("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( is_file("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("s",'ImageFiles/' . $_FILES['fileImage']['name']);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("s",'ImageFiles/' . $_FILES['fileImage']['name']);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
}
}
?>
Below is the old mysql code where the insert did work:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$result = 0;
if(getimagesize($_FILES['fileImage']['tmp_name'])){
if( is_file("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( is_file("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
}
mysql_close();
?>
<script language="javascript" type="text/javascript">
window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');
</script>
Try this, assign the value to a variable first and then bind it, dont build the data within the bind_param:
<?php
$imagesql = "INSERT
INTO Image (ImageFile)
VALUES (?)";
$insert = $mysqli->prepare($imagesql);
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
?>
Also you should check if the file is uploaded and if any errors have occurred with the upload before doing any db stuff:
<?php
//If POST
if($_SERVER['REQUEST_METHOD']=='POST'){
//Check no errors on upload
if($_FILES['fileImage']['error']==0){
if(isset($_FILES['fileImage']['tmp_name'])){
$imgSize = getimagesize($_FILES['fileImage']['tmp_name']);
...
...
}
}else{
//get error code and display error
}
}else{
//No POST
}
?>
Related
I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.
Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.
File Path with '/' is not passing using $open = fopen('$cont[$x]','r');
<?php
//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');
$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);
$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
// $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
$dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");
if(mysqli_num_rows($dup)>0)
{
echo "File already Exists";
}
else {
$insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
// $conn->query($insert);
if (mysqli_query($conn,$insert)) {
$open = fopen('$cont[$x]','r');
while (!feof($open))
{
$content = fgets($open);
$carry = explode(",",$content);
list($name,$city,$postcode,$job_title) = $carry;
$sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
$conn->query($sql);
}
fclose($open);
echo 'inserted';
} else {
echo 'Not inserted';
}
}
}
?>
I'm making a form for some project. The problem is when the user enter their data using the field and then submit, the input not keep in the database.
Also when clicking submit the direct page show blank empty page even the connection test also not showing.
I'm using almost similar code for other project and it work except for this.
below is my code:
<?php
//check connection
require 'config.php';
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//asas (table name)
$id = $_POST["Sid"]; $ic = $_POST["Sic"];
$name = $_POST["Snp"]; $jant = $_POST["J1"];
$trum = $_POST["Chr"];$tbim = $_POST["Chp"];
$mel = $_POST["Sem"]; $arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"]; $uni = $_POST["Sis"];
$bid = $_POST["tpe"];$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];$bik = $_POST["B1"];
$tem = $_POST["te"];$mula = $_POST["tm"];
$tamm = $_POST["tt"]; $res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];$keb = $_POST["fileToUpload3"];
$link = mysqli_connect($h,$u,$p,$db);
if('id' != '$Sid'){
$asas = "insert into asas Values ('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values ('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
mysqli_query($link,$asas);
mysqli_query($link,$inst);
mysqli_query($link,$indr);
mysqli_close($link);
}
else
{
echo "failed"
}
?>
<b>Register complete</b>
Can anybody tell me what the error or maybe some solution. Thanks
I think you are having problem in insert query, please check this:
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
Write this kind.
thank you
there are few issues with the code like variable id was used without $
and need to use die method with mysqli_query() function to check for
errors, please check below improved codes, it may help you -
<?php
//check connection
require 'config.php';
if (isset($_POST)) {
//asas (table name)
$id = $_POST["Sid"];
$ic = $_POST["Sic"];
$name = $_POST["Snp"];
$jant = $_POST["J1"];
$trum = $_POST["Chr"];
$tbim = $_POST["Chp"];
$mel = $_POST["Sem"];
$arum = $_POST["Ar"];
$asum = $_POST["As"];
//institusi
$thp = $_POST["T1"];
$uni = $_POST["Sis"];
$bid = $_POST["tpe"];
$Aint = $_POST["Ai"];
//industri
$bip = $_POST["bid"];
$bik = $_POST["B1"];
$tem = $_POST["te"];
$mula = $_POST["tm"];
$tamm = $_POST["tt"];
$res = $_POST["fileToUpload1"];
$tran = $_POST["fileToUpload2"];
$keb = $_POST["fileToUpload3"];
}
$link = mysqli_connect($h, $u, $p, $db);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
// if('id' != '$Sid'){
if ($id != '$Sid') {
$asas = "insert into asas Values
('$id','$ic','$name','$jant','$trum','$tbim','$mel','$arum','$asum')";
$inst = "insert into institusi Values ('$thp','$uni','$bid','$Aint')";
$indr = "insert into industri Values
('$bip','$bik','$tem','$mula','$tamm','$res','$tran','$keb')";
if (mysqli_query($link, $asas)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $inst)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
if (mysqli_query($link, $indr)) {
echo "records inserted";
} else {
echo "failed".mysqli_error($link) ;
}
}
mysqli_close($link);
?>
<b>Register complete</b>
just use or die after mysqli_query
mysqli_query($link,$asas)or die ('Unable to execute query. '. mysqli_error($link));
you will get to know what is the actual problem
I am new in PHP and I'm currently working with a module of Setting an operation wherein I will insert data from a modal into the database. There's no error in terms of getting the data but when I click the button, the "Query failed: INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('vbv','12:09','17:09','4')" always being displayed.
Here's the code for the db class..
var $hostname = "REDACTED";
var $username = "REDACTED";
var $password = "REDACTED";
var $database = "REDACTED";
function select_db() {
$result = mysqli_connect($this->hostname,$this->username,$this->password);
if (!mysqli_select_db( $result, $this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result1 = mysqli_connect($this->hostname,$this->username,$this->password);
$result = mysqli_query($result1,$query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysqli_fetch_array($result);
}
function num_rows($result) {
return mysqli_num_rows($result);
}
function last_insert_id() {
return mysqli_insert_id();
}
function kill() {
mysqli_close();
}
}
?>
and here's the code for inserting the data.
<?php
if (isset($_POST['btnSubmit'])) {
$db = new mysqldb();
$db->select_db();
$result1 = mysqli_connect("REDACTED","REDACTED","REDACTED");
$sql_mobilvis = sprintf("INSERT INTO tbl_mobilvis (location, timestart, timeend, mobilnum) VALUES ('%s','%s','%s','%s')",
mysqli_real_escape_string($result1,$_POST['location']),
mysqli_real_escape_string($result1,$_POST['starttime']),
mysqli_real_escape_string($result1,$_POST['endtime']),
mysqli_real_escape_string($result1,$_POST['mobilnum']));
$result_user = $db->query($sql_mobilvis);
if ($_POST['fields']){
$inserted_mobilvis_id = $db->last_insert_id();
foreach ( $_POST['fields'] as $key=>$value ) {
$sql_enforcer = sprintf("INSERT INTO tbl_mobilenforcer (enforcername) VALUES ('%s')",
mysqli_real_escape_string($result1, $value) );
$result_website = $db->query($sql_enforcer);
$inserted_enforcer_id = $db->last_insert_id();
$sql_mobil_enforcer = sprintf("INSERT INTO tbl_mobil (mobilid, mobilenforcerid) VALUES ('%s','%s')",
mysqli_real_escape_string($result1,$inserted_mobilvis_id),
mysqli_real_escape_string($result1,$inserted_enforcer_id) );
$result_mobil_enforcer= $db->query($sql_mobil_enforcer);
}
} else {
echo "<script>alert('no added enforcers')</script>";
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> enforcers are added!</h1>";
$db->kill();
}
?>
Why I am getting this Query failed?
in mysql Datbase there is images stored using php Script (image got from a form.html/POST method) let's cal them (phpImages). and there is others stored using android application ( by converting Bitmap to String and using StringBuilder ). let's call them (androidImages).
with this php script i can load and display phpImages, but i cannot display androidImages.
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo ( $result['image']);
mysqli_close($con);
}
?>
with this php script i can load androidImages, but i cannot load phpImages :
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo base64_decode( $result['image'] );
mysqli_close($con);
}
?>
i wan't a php script that could display the both. because i want to load all images in a ListView of an android Apps.
**This is php script relied to android Application : **
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$con=mysqli_connect("localhost","root","","othmane")or die(mysqli_error($con));
$sql = "INSERT INTO images (image,image_type) VALUES (?,'android')";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
this is php Script relied with Form.html post method :
<?php
echo ini_get( 'file_uploads' );
if(!isset($_POST['submit'])){
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
function upload(){
$imgfp = fopen($_FILES['photo']['tmp_name'], 'rb');
print_r($_FILES);
$dbh = new PDO("mysql:host=localhost;dbname=othmane", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO images (image,image_type) VALUES (?,'php')");
$stmt->bindParam(1, $imgfp, PDO::PARAM_LOB);
$stmt->execute();
}
?>
Add a column called image_type in your table and pass one of the following values to determine what the source of the image is upon uploading: phpImage or androidImage
So you can do:
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = $_GET['id'];
$sql = "SELECT image, image_type FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));
$result = mysqli_fetch_array($r);
header('Content-Type: image/jpeg');
if ($result['image_type'] == 'phpImage') {
echo ( $result['image']);
} else if ($result['image_type'] == 'androidImage') {
echo base64_decode( $result['image'] );
}
mysqli_close($con);
}
?>
So i am having this issue. The code is for art gallery calendar. The code has worked for this day but now it has broken down. I wrote it about 1-2 months ago and now they contacted me that something is wrong. Here is the code
<?php
require('config.php');
if(isset($_POST['lisaa_pvm'])) {
$alkupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['alkupvm'])));
$loppupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['loppupvm'])));
$muuta = mysql_real_escape_string($_POST['muuta']);
$result = mysql_query("INSERT INTO kipina_kalenteri VALUES ('','$alkupvm','$loppupvm','','','','','$muuta')") or die (mysql_error());
$tapahtuma_id = mysql_insert_id();
header('location: lisaa_tapahtuma.php?tid='.$tapahtuma_id);
}
if(isset($_POST['lisaa_tapahtuma'])) {
// siivotaan syƶtteet
foreach ($_POST as $key => $value) {
mysql_real_escape_string($value);
${"$key"} = $value;
}
$url = ROOT.'/files/';
if($_FILES['kuva1']['size'] > 0) {
$target = $url . $_FILES['kuva1']['name'];
if(move_uploaded_file($_FILES['kuva1']['tmp_name'], $target)) {
$kuva[] = "kuva_1 = '".basename( $_FILES['kuva1']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva2']['size'] > 0) {
$target = $url . basename( $_FILES['kuva2']['name']);
if(move_uploaded_file($_FILES['kuva2']['tmp_name'], $target)) {
$kuva[] = "kuva_2 = '".basename( $_FILES['kuva2']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva3']['size'] > 0) {
$target = $url . basename( $_FILES['kuva3']['name']);
if(move_uploaded_file($_FILES['kuva3']['tmp_name'], $target)) {
$kuva[] = "kuva_3 = '".basename( $_FILES['kuva3']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if(isset($kuva)) {
$kuvat = ", ".implode(',',$kuva);
}
if(isset($sama) AND $sama != '') {
$update = "UPDATE kipina_kalenteri SET $paikka = $sama $kuvat WHERE id = $kalenteri";
mysql_query($update) or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} elseif(isset($update)) {
$update = "UPDATE kipina_tapahtuma SET
taiteilija = '$taiteilija',
nimi = '$nimi',
kuvaus = '$kuvaus',
kuvaus = '$lyhyt_kuvaus'
$kuvat
WHERE
id = $update";
$result = mysql_query($update) or die (mysql_query());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} else {
$insert = mysql_query("INSERT INTO kipina_tapahtuma VALUES ('','$taiteilija','$nimi','$lyhyt_kuvaus','$kuvaus','$kuva[0]','$kuva[1]','$kuva[2]')") or die (mysql_error());
$tid = mysql_insert_id();
$update = mysql_query("UPDATE kipina_kalenteri SET $paikka = $tid WHERE id = $kalenteri") or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
}
}
I hope i get answer soon
Someone added or deleted one of the columns in table kipina_kalenteri or kipina_tapahtuma. Because of such situations it's better to always declare to which columns you want to insert.
So it should be like that:
INSERT INTO table (`column1`, `column2`) VALUES ('values1', 'values2');
It's about your table fields. Please define the table field before you start insert a data:
$result = mysql_query("INSERT INTO kipina_kalenteri (`field1`,`field2`,`field3`) VALUES ('$alkupvm','$loppupvm','$muuta')") or die (mysql_error());
so you can sure if the fields are matched with your data