目錄
回复讨论(解决方案)
首頁 後端開發 php教程 当执行mysql insert 时插入两条是怎么回事?

当执行mysql insert 时插入两条是怎么回事?

Jun 23, 2016 pm 02:16 PM

本帖最后由 Eason_____________ 于 2013-07-25 11:25:44 编辑

MySQL 数据库

//做了一个手机上传图片到服务器的功能。但是获取到执行insert语句时都要执行两次!

//index.php
<?phpheader("Content-Type: text/html; charset=UTF-8");mysql_connect("localhost","dome_huayan","e2k3e6b8");mysql_select_db("dome_huayan");mysql_query("set names utf8");include 'uploadImage.php';$gettitle=$_GET['title'];$getcontent=$_GET['content'];$i = new uploadImage($_FILES['filename'],'./img/');$i->doWork();$i->imageCheck();$sql="insert into json_bbs values('','".$gettitle."','".$getcontent."','".$i->iamgePath."','".time()."','')";mysql_query($sql);?>
登入後複製


//uploadImage.php

<?php/** *  * 图片上传类 * @author ChenYue * * @param $mageStauts                 图片上传状态 1为正常状态 * @param $iamgePath                  图片上传成功保存在数据库的路径 * @param $imagePathTemp              临时保存图片上传成功保存在数据库的路径 * @param $destination_folder 	      上传文件路径 * @param $imageName                  上传的图片名(可自定义) * @param $fileArray                  上传的图片信息数组 * @param $updateImage                判断是否更新原有图片 0表示不更新 , 1 表示更新 * @param $uptypes                    支持上传的图片类型 * @param max_file_size               支持上传的图片最大类型 * @param imageType                   图片的类型 * */class uploadImage{		public $imageStauts = 1;	public $iamgePath=''; 	public $imagePathTemp = "";	private $destination_folder; 	private $imageName; 	private $fileArray;	private $updateImage = 0; 	private $uptypes = array(    'image/jpg',    'image/jpeg',    'image/png',    'image/x-png');    private $imageType = array('jpg','jpeg','png');	const max_file_size=2000000;     		/**	 * 构造函数		 * @param $file 上传的图片信息数组	 * @param $destination 上传文件路径	 * @param $name 上传的图片名(可自定义)没定义,上传后的图片名为time()	 * @param $dbPath 图片上传成功保存在数据库的路径	 * @param $update 判断是否更新原有图片 0表示不更新 , 1 表示更新 。 更新会把已经存在的图片替换掉	*/		function __construct($file,$destination="",$name="",$dbPath="",$update=0){				if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){			$this->imageStauts = 'Error! Wrong HTTP method!';		}		if(is_array($file) && count($file)>0 && !empty($destination)){			$this->fileArray = $file;			$this->destination_folder = $destination;			$this->imageName = $name;			$this->imagePathTemp = $dbPath;			$this->updateImage = $update;		}else{						$this->imageStauts =  '初始化失败';		}			}		/**	 * 开始图片上传	*/	function imageStart(){		if($this->imageStauts === 1){			$this->imageCheck();					}		if($this->imageStauts === 1){			$this->doWork();		}	}	/**	* 	* 图片的检查工作	*/	function imageCheck(){		$file = $this->fileArray;		//print_r($file);		if(!is_uploaded_file($file['tmp_name']) && $this->imageStauts === 1){			$this->imageStauts =   '图片不存在!';         			}		if(uploadImage::max_file_size < $file['size'] && $this->imageStauts === 1){			$this->imageStauts =  '文件太大';		}                /*		//检查mime-type		if(!in_array(strtolower($file['type']), $this->uptypes) && $this->imageStauts === 1){			$this->imageStauts =  '不支持 '.$file['type'].' 类型的文件';		}                */		//防止在图片元数据的Comment字段中加入了php代码		//通过二进制匹配检查		$fileInfo = pathinfo($this->fileArray['name']);		$fileType = strtolower($fileInfo['extension']);		if(!in_array($fileType, $this->imageType) && $this->imageStauts === 1){			$this->imageStauts =  '不支持 '.$fileType.' 类型的文件';		}                		if(!file_exists($this->destination_folder) && $this->imageStauts === 1){			mkdir($this->destination_folder,0777);//设置文件权限		}	}	/**	 * 	 * 开始图片上传的工作	*/	function doWork(){		$fileName = $this->fileArray['tmp_name'];		$fileSize = getimagesize($fileName);		$fileInfo = pathinfo($this->fileArray['name']);		$fileType = strtolower($fileInfo['extension']);		$n = !empty($this->imageName) ? $this->imageName : date("Y_n_d_H_i_s");		$destination = $this->destination_folder.$n.'.'.$fileType;//图片本地路径		$this->imagePathTemp = $this->imagePathTemp.$n.'.'.$fileType;//将要保存在数据库的路径		//上传图片,若图片存在不更新已有图片		if(file_exists($destination) && $this->imageStauts === 1 && $this->updateImage == 0){			$this->imageStauts =  '图片已存在';		}		//上传图片,若图片存在更新已有图片		if($this->imageStauts === 1 && $this->updateImage == 1){			$deleteIMageDestination = $this->destination_folder.$n; //图片保存本地路径,包含文件名,但不包含图片后缀名			if($this->deleteImage($deleteIMageDestination)){			}else{				$this->imageStauts = '删除已存在图片失败';			}		}		if(!move_uploaded_file($fileName, $destination) && $this->imageStauts === 1){			$this->imageStauts =  '传输错误';		}		if($this->imageStauts === 1){			$this->iamgePath = $this->imagePathTemp;			return $this->imageStauts;		}							}	/**	 * 删除图片	 * @param $path  图片在本地的保存路径	 * @return 成功返回1 失败返回0	*/	function deleteImage($path){		if(!empty($path)){			foreach($this->imageType as $type){				$_path = $path.'.'.$type;				if(file_exists($_path)){					//echo $_path;					if(!unlink($_path)){						$this->imageStauts = '删除已存在图片失败';						return 0;					}				}			}			return 1;		}else{			$this->imageStauts = '待删除图片路径不能为空';			return 0;		}	}}?>
登入後複製


回复讨论(解决方案)

求帮忙看看!

index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?

index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?
还有就是js传过来的 title 和 content

index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?

如果判断一下index.php

if($_GET['title']!=''){$sql="insert into json_bbs values('','".$gettitle."','".$getcontent."','".$i->iamgePath."','".time()."','')";mysql_query($sql);}
登入後複製
登入後複製


在执行的话 就只插入一条数据了,但是获取不到$i->iamgePath的值,$i->iamgePath就为空。

不判断的话 是插入以下两条数据:
id title content images time uid
127 aaa yyyyy 1374722311 0
128 2013_7_25_11_18_32.jpg 1374722312 0


index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?
还有就是js传过来的 title 和 content

js传来的title和content?怎么传递的
会不会js传递时执行了脚本,提交上传图片时又执行了insert。所以是两条记录?


index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?

如果判断一下index.php

if($_GET['title']!=''){$sql="insert into json_bbs values('','".$gettitle."','".$getcontent."','".$i->iamgePath."','".time()."','')";mysql_query($sql);}
登入後複製
登入後複製


在执行的话 就只插入一条数据了,但是获取不到$i->iamgePath的值,$i->iamgePath就为空。

不判断的话 是插入以下两条数据:
id title content images time uid
127 aaa yyyyy 1374722311 0
128 2013_7_25_11_18_32.jpg 1374722312 0


你这个一看就是2个不同操作执行得到的插入
你这2个动作,一个应该是更新动作,应该说是后来执行的那个动作只能是更新动作,不能是插入动作

所以你本身逻辑上出现了问题,插入2条数据属于正常的

看看你的表单

看看你的表单



index.php 代码就只有这些?
是不是执行后又刷新了?跳转了?
还有就是js传过来的 title 和 content

js传来的title和content?怎么传递的
会不会js传递时执行了脚本,提交上传图片时又执行了insert。所以是两条记录?

json传递的


看看你的表单

斑竹说表单,你给数据库。。
是表单部分的代码和js部分的代码。



看看你的表单

斑竹说表单,你给数据库。。
是表单部分的代码和js部分的代码。

ajax?
传递过来不就执行insert了么?
提交表单又执行一次。
不就刚好两条数据么


看看你的表单


<!DOCTYPE html><html class="um landscape min-width-240px min-width-320px min-width-480px min-width-768px min-width-1024px">  <head>    <title>    </title>    <meta charset="utf-8">    <meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">    <link rel="stylesheet" href="css/ui-input.css">    <link rel="stylesheet" href="css/ui-btn.css">    <link rel="stylesheet" href="css/ui-img.css">    <link rel="stylesheet" href="css/ui-list.css">    <link rel="stylesheet" href="css/ui-res.css">    <link rel="stylesheet" href="css/ui-fold.css">    <link rel="stylesheet" href="css/ui-base.css">    <link rel="stylesheet" href="css/ui-box.css">    <link rel="stylesheet" href="css/ui-color.css">    <script src="js/zy_anim.js">    </script>    <script src="js/zy_control.js">    </script> 	<script src="js/zy_tmpl.js">    </script>	<script src="js/zy_click.js">    </script>	<script src="js/zy_json.js">    </script>    </head>  <body class="um-vp" ontouchstart><div class="btm" id="yinying" style="display:none"></div><div class="c-wh" id="fb_content">    	     <!--文本开始-->    <div class="ub t-bla ulab">      <div class="ub-f1 c-wh uba uc-a1 b-gra us-i uinput uinn4" style="margin-top:5%">      <input placeholder="标题..."  type="text" name="title" class="uc-a1" id="fb-title">       </div>    </div>    <!--文本结束-->    <!--文本开始-->    <div class="ub t-bla ulab fb-btn">      <div class="ub-f1 c-wh uba uc-a1 b-gra us-i uinput uinn4">      <textarea  placeholder="请输入内容"  name="content" rows="7" id="fb-content" ></textarea>    </div>    </div>    <!--文本结束-->    <div style=" display:none; width:20%; height:15%; margin-top:5%; left:1%" id="show_img">    	<span class="del" onClick="del()">x</span>        <img  src="/static/imghw/default1.png"  data-src="" id="  class="lazy"    style="max-width:90%"  id="showPic" / alt="当执行mysql insert 时插入两条是怎么回事?" >            </div>	<!--按钮开始-->    <div ontouchstart="zy_touch('btn-act')" class="btn uba b-bla uinn5 c-blu1 c-m2 uc-a1 t-wh img-add"  onclick="picSeclet();" id="selectPic">添加图片</div>	<!--按钮结束-->    	<!--按钮开始-->    <div ontouchstart="zy_touch('btn-act')" class="btn uba b-bla uinn5 c-blu1 c-m2 uc-a1 t-wh img-add" onClick="upload()">发布</div>	<!--按钮结束-->    <div style="position:absolute; bottom:0; width:100%; z-index:100; display:none" id="divPic">             <div ontouchstart="zy_touch('c-m2');" data-role="button" onclick="uexImageBrowser.pick();" class="btn uba b-bla uinn5 c-bla c-m1 uc-a1 t-wh img-add1">                     <span class="ui-btn-inner ui-btn-corner-all">                     <span class="ui-btn-text t-wh">从手机相册选择</span>                     </span>            </div>             <div ontouchstart="zy_touch('c-m2');" data-role="button" onclick="uexCamera.open();" class="btn uba b-bla uinn5 c-bla c-m1 uc-a1 t-wh img-add1">                     <span class="ui-btn-inner ui-btn-corner-all">                     <span class="ui-btn-text t-wh">拍照</span>                     </span>            </div>            <div ontouchstart="zy_touch('c-m2');" data-role="button" onclick="picClose();" class="btn uba b-bla uinn5 c-bla c-m1 uc-a1 t-wh img-add1">                     <span class="ui-btn-inner ui-btn-corner-all">                     <span class="ui-btn-text t-wh">取消</span>                     </span>            </div>    </div></div></body><script>zy_init();window.uexOnload=function(type){	if(!type){		uexWindow.setBounce("1");		uexWindow.showBounceView("0","#FFF","0");		uexWindow.showBounceView("1","#FFF","0");	}}        var uploadHttp = "http://www.huayan.cd/json/bbs/index.php";        function setLog(msg){                document.getElementById("msgid").innerHTML = msg;        }        function upload(){				if($$("fb-title").value=='' || $$("fb-content").value==''){					alert("标题或内容不能为空");				}else{					uexUploaderMgr.createUploader(1,uploadHttp);					var fbtitle = $$("fb-title").value;					var fbcontent = $$("fb-content").value;					var url = 'http://localhost/json/bbs/index.php?title='+fbtitle+'&content='+fbcontent;					$.getJSON(url,function(data){						alert(data.title);						alert(data.content);						alert(data.time);						alert(data.time1);					});				}        }        function picSeclet(){                document.getElementById("yinying").style.display = "block";                document.getElementById("divPic").style.display = "block";        }        function picClose(){                document.getElementById("yinying").style.display = "none";                document.getElementById("divPic").style.display = "none";        }        function del(){                document.getElementById("show_img").style.display = "none";                document.getElementById("showPic").src = "";        }        var upload_image_url = "";        window.uexOnload = function(){                uexCamera.cbOpen = function(opCode, dataType, data){                        upload_image_url = data;                        document.getElementById("showPic").src = data;                        document.getElementById("show_img").style.display = "block";                        document.getElementById("divPic").style.display = "none";						document.getElementById("yinying").style.display = "none";                }				                uexWidgetOne.cbError = function(opCode, errorCode, errorInfo){                        setLog(errorInfo);                }                                uexImageBrowser.cbPick=function (opCode,dataType,data){		        if(dataType==0){									upload_image_url = data;	              				document.getElementById("showPic").src = data;									document.getElementById("show_img").style.display = "block";									document.getElementById("yinying").style.display = "none";									document.getElementById("divPic").style.display = "none";		        }	           }	                uexUploaderMgr.cbCreateUploader =function(opCode,dataType,data){                        if(data == 0){                                        uexUploaderMgr.uploadFile(1,upload_image_url,"filename",4);                                        uexWindow.toast(1,5,"图片上传中...",0);                        }else{                        }                                        }				                uexUploaderMgr.onStatus = function(opCode,fileSize,percent,serverPath,status){                        switch (status) {                                        case 0:                                                break;                                        case 1:                                                uexWindow.closeToast();//关闭提示消息框                                                uexWindow.toast(0,5,"发布成功!",2000);                                                //uexWindow.closeToast();//关闭提示消息框                                                uexUploaderMgr.closeUploader(1);                                                break;                                        case 2:                                                uexWindow.closeToast();//关闭提示消息框                                                uexWindow.toast(0,5,"出错啦~",2000);                                                uexUploaderMgr.closeUploader(1);                                                break;                        }                                        }        }</script></html>
登入後複製




看看你的表单

斑竹说表单,你给数据库。。
是表单部分的代码和js部分的代码。

ajax?
传递过来不就执行insert了么?
提交表单又执行一次。
不就刚好两条数据么

如果我判断一下 

就是 if($_GET["title"]!=''){

}
就执行了一次。

但是插入的数据 $i->iamgePath的值就为空 这个是怎么回事?

你的文字提交和文件上传本身就是分开的

你的文字提交和文件上传本身就是分开的
嗯 这是我用appcan做的手机app.

你的文字提交和文件上传本身就是分开的

现在插入两条的问题解决了  就是插入的时候 获取不到$i->iamgePath的值。 
但是当insert 是两条的时候 $i->iamgePath就会有。

这是在提交文字
105 var url = 'http://localhost/json/bbs/index.php?title='+fbtitle+'&content='+fbcontent;
106 $.getJSON(url,function(data){

这是在提交文件
152 uexUploaderMgr.uploadFile(1,upload_image_url,"filename",4);        

虽然在文本提交前就启动了文件提交
102 uexUploaderMgr.createUploader(1,uploadHttp);

但一般文件上传总要慢于文本提交,所以你能先收到 get 数据,后收到 上传文件
但如果情况恰恰相反呢?


你的文字提交和文件上传本身就是分开的

现在插入两条的问题解决了  就是插入的时候 获取不到$i->iamgePath的值。 
但是当insert 是两条的时候 $i->iamgePath就会有。
给你一个思路和建议,其实不少网站也在用,就是:
上图图片部分用iframe,在ajax提交的是时候先执行上图图片部分,然后得到返回正常的图片地址(这里还不插入数据库,纯粹上传图片)以后再执行再执行文字表单部分,这时候图片地址是用一个参数传,这样就可以和文字一起插入数据库了,也就只有一条数据了



你的文字提交和文件上传本身就是分开的

现在插入两条的问题解决了  就是插入的时候 获取不到$i->iamgePath的值。 
但是当insert 是两条的时候 $i->iamgePath就会有。
给你一个思路和建议,其实不少网站也在用,就是:
上图图片部分用iframe,在ajax提交的是时候先执行上图图片部分,然后得到返回正常的图片地址(这里还不插入数据库,纯粹上传图片)以后再执行再执行文字表单部分,这时候图片地址是用一个参数传,这样就可以和文字一起插入数据库了,也就只有一条数据了

谢谢两位版主给的思路。 我在试一试

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1322
25
PHP教程
1269
29
C# 教程
1249
24
說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

See all articles