Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 当执行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);?>
Copy after login


//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;		}	}}?>
Copy after login


回复讨论(解决方案)

求帮忙看看!

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);}
Copy after login
Copy after login


在执行的话 就只插入一条数据了,但是获取不到$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);}
Copy after login
Copy after login


在执行的话 就只插入一条数据了,但是获取不到$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>
Copy after login




看看你的表单

斑竹说表单,你给数据库。。
是表单部分的代码和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提交的是时候先执行上图图片部分,然后得到返回正常的图片地址(这里还不插入数据库,纯粹上传图片)以后再执行再执行文字表单部分,这时候图片地址是用一个参数传,这样就可以和文字一起插入数据库了,也就只有一条数据了

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles