没有数据时,PHP代码无法正常工作?

时间:2013-01-24 09:02:23

标签: php mysql ajax uploadify

我正在做基于PHP的数据输入程序,每件事都没有问题(仍在建设中)但是有一个问题我无法找到解决方案。问题是当数据库没有任何数据时,图像路径不会被注册。

现在,我正在使用uplodify上传图像文件,同时我也在发送一些数据。数据包含一个名称,联系方式和描述,这将直接插入到数据库中,我还上传图像,该图像将保存到文件夹中,名称将保存在数据库中。但是这个过程由两个不同的PHP文件处理,一个是处理数据添加的AddPOIPro.PHP,另一个是用于处理文件上传和文件名更新的uplodify.php。

我遇到的第一个问题是uplodify并没有在提交数据的同一行中添加文件名,所以我所做的是获取最后一个ID并将其递减1并更新当有数据时有效的行但当他们没有数据失败时。那么我应该怎么做呢?以下是我的完整脚本,谢谢您的时间。

表格

<?php

/**
 * @author SiNUX
 * @copyright 2013
 */

include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>

<script type="text/javascript">
$(function() {
    $('#imgUpload').uploadify({
        'auto'     : false,
        'swf'      : 'Upl/uploadify.swf',
        'uploader' : 'Upl/uploadify.php',
        'height'   : 20,
        'width'    : 200,
    }
        // Put your options here
    });
});
</script>

<script type="text/javascript">
 $(document).ready(function(){
  $("#sendData").click(function(){
    var name  = document.getElementById("Name").value;
    var desc = document.getElementById("Descrip").value;
    var con = document.getElementById("ConInfo").value;
    var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;

    $.ajax({
      type:'POST',
      data:dataString,
      url:'AddPoiPro.php',
      success:function(data){
       if(data="Data inserted") {
          //alert("Data  Success");
          document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
          $('#msg').delay(1500).fadeOut();

        } else {
          //alert("Not Inserted");
          document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
        }
     } 
   });
  });
});
</script>

<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />

<title>AddPOI</title>
</head>

<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
  <p>
    <label for="poiid">ID :</label>
    <input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
  </p>
  <p>
    <label for="Name">POI Name :</label>

    <input type="text" name="Name" id="Name" />
  </p>
  <p>
    <label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
    <textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
  </p>
  <p>
    <label for="ConInfo">Contact Infomation :</label>
    <textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
  </p>
  <p>
    <label for="Img">POI Image</label>
    <input type="file" name="imgUpload" id="imgUpload" />
  </p>
  <p><div id="msg"></div></p>
  <p>  
  <div align="center">
    <input type="button" name="Submit" id="sendData" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
    <input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
  </div>
  </p>
</form>
</body>
</html>

处理PHP

<?php

/**
 * @author SiNUX
 * @copyright 2013
 */

include ('connect.php');

$getId = mysql_query("SELECT ID FROM poiinfo");
$row = mysql_fetch_array($getId);

$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];

if($row['ID']== 1){

    $updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
    $updDone = mysql_query($updLn);
    if ($updDone){
        echo "Data inserted";
    }else {
        echo "Not Done";
    }  

}else {
 $dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";

        $putData = mysql_query($dbData);
        if ($putData){
            echo "Data inserted";
        }else {
            echo "Not Done";
        }
 }       
?>

uplodify php

<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');


// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root

/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);

        echo $fName;
        echo '1';
    } else {
        echo 'Invalid file type.';
    }
}*/

//if (!empty($_FILES)) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetFile = $targetPath . $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);    
    $tId = $tId--;


    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);

        $fName = $_FILES['Filedata']['name'];
        $imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
        mysql_query($imgPath);  

     echo '1';       

    } else {
        echo 'Invalid file type.';
    }
?>

请帮忙。

3 个答案:

答案 0 :(得分:0)

要获得最后一个ID,您可以像以下一样进行查询

SELECT `ID`
FROM `poiinfo`
ORDER BY `ID` DESC
LIMIT 0 , 1

如果你遇到更多问题,那么你可以敲我......

答案 1 :(得分:0)

我认为这是一种更好的方法

 $("#sendData").click(function(){
    //upload the file programatically (Method Call'upload')[http://www.uploadify.com/documentation/uploadify/upload/]
    // echo the name of the uploaded file (make sure to rename the file for uniquiness)
    // create a hidden element with the filename as the value inside the form
    // call the ajax submit and submit the form. You can use (onuploadsuccess)[http://www.uploadify.com/documentation/uploadify/onuploadsuccess/] to trigger the element creation and ajax submit functions
 });

您当前的实施可能会导致问题考虑,
 请求1:ID 10
 上传1:ID 10
 要求2:ID 11
 要求3:ID 12
 上传2:ID 12
 上传3:ID 12

答案 2 :(得分:0)

我发现我的问题的解决方案在StackOverflow中得到了一些帮助下面是我的完整代码是任何一个有类似我的相同问题你可以使用这个代码。如果它适合你,请投票给我谢谢。

我的数据输入表单

<?php

/**
 * @author SiNUX
 * @copyright 2013
 */

include ('lId.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>

<script type="text/javascript">
$(function() {
    $(function() {
        $('#imgUpload').uploadify({
            'auto'     : false,
            'swf'      : 'Upl/uploadify.swf',
            'uploader' : 'Upl/uploadify.php',
            'height'   : 20,
            'width'    : 200,
            'fileTypeDesc' : 'Image Files',
            'fileTypeExts' : '*.gif; *.jpg; *.png'
    });
        // Put your options here
    });
});
</script>

<script type="text/javascript">
 $(document).ready(function(){
  $("#save_data").click(function(){
    var name  = document.getElementById("Name").value;
    var desc = document.getElementById("Descrip").value;
    var con = document.getElementById("ConInfo").value;

    var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;

    $.ajax({
      type:'POST',
      data:dataString,
      url:'AddPoiPro.php',
      success:function(data){
       if(data="Data inserted") {
          //alert("Data  Success");
          document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
          $('#msg').delay(1500).fadeOut();
        } else {
          //alert("Not Inserted");
          document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
          $('#msg').delay(1500).fadeOut();
        }
     } 
   });
  });
});
</script>

<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />

<title>AddPOI</title>
</head>

<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
  <p>
    <label for="poiid">ID :</label>
    <input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
  </p>
  <p>
    <label for="Name">POI Name :</label>

    <input type="text" name="Name" id="Name" />
  </p>
  <p>
    <label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
    <textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
  </p>
  <p>
    <label for="ConInfo">Contact Infomation :</label>
    <textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
  </p>
  <p>
    <label for="Img">POI Image</label>
    <input type="file" name="imgUpload" id="imgUpload" />
  </p>
  <p><div id="msg"></div></p>
  <p>  
  <div align="center">
    <input type="button" name="Submit" id="save_data" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
    <input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
  </div>
  </p>
</form>
</body>
</html>

我的DataProcess PHP

<?php

/**
 * @author SiNUX
 * @copyright 2013
 */

include ('connect.php');

$getId = mysql_query("SELECT ID FROM dbname");
$row = mysql_fetch_array($getId);

$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];

if($row['ID']== 1){

    $updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
    $updDone = mysql_query($updLn);

    if ($updDone){
        echo "Data inserted";
    }else {
        echo "Not Done";
    }  

}else {
    $dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";        
    $putData = mysql_query($dbData);

    if ($putData){
        echo "Data inserted";
    }else {
        echo "Not Done";
    }
 }       
?>

这对于uploadify PHP来说真的很棘手,但让它以我想要的方式工作。

Uplodify PHP(我的版本)

<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');


// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root

/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);

        echo $fName;
        echo '1';
    } else {
        echo 'Invalid file type.';
    }
}*/

//if (!empty($_FILES)) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetFile = $targetPath . $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // File extensions
    $fileParts = pathinfo($_FILES['Filedata']['name']);    
    $tId = $tId--;


    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);

        $fName = $_FILES['Filedata']['name'];
        $imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
        mysql_query($imgPath);  

     echo '1';       

    } else {
        echo 'Invalid file type.';
    }
?>

如果有些人遇到我面临的相同情况,并且看看它是否适合您,并且您也可以进行任何更改,那么此脚本现在可以正常运行。

谢谢。