Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 关于PHP更新数据库

关于PHP更新数据库

Jun 23, 2016 pm 02:12 PM

本帖最后由 UR_Not_Alone 于 2013-06-03 11:55:36 编辑

刚开始学PHP遇到一些基础问题请大家帮忙
从网上看的一个例子,做了下练习。
我填好页面内容点击提交时,页面默认打开insert.php,而不是执行insert.php中代码插入数据库是怎么回事啊。
代码如下
Html页面
<!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" /><title>无标题文档</title></head><body><form action="insert.php" method="post" target="win">请输入新闻的title:<input type="text" name="title" />请选择新闻类型:<select name="c_id"><option value="1">体育</option><option value="2">娱乐</option></select><br />请输入新闻的content:<br /><textarea cols="60" rows="15" name="content"></textarea><input type="submit" value="提交" /></form></body></html>
Copy after login


insert.php
<?phpinclude("connect_mysql.php");$q = "insert into new(title,content,time,news_cate_id) values('".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";mysql_query($q);if(mysql_affected_rows()>0) echo "xinwentianjiachenggong!";?><hr /><a href="add_news.php" target="win">fanhuijixutianjiaxinwen</a>
Copy after login


connect_mysql.php
<?phpfunction mysql_open(){$mysql_servername="localhost"; //$mysql_username="root";$mysql_password="11111";$mysql_dbname="new";$conn=mysql_connect($mysql_servername ,$mysql_username ,$mysql_password);      mysql_query("set names UTF8"); //UTF8      mysql_select_db($mysql_dbname , $conn);	  return $conn;}?>
Copy after login


另外,如果我想实现上传图片的功能该怎么做啊,求提供思路,如果有人有例子最好了,谢谢大家


回复讨论(解决方案)

include("connect_mysql.php");
mysql_open();

include("connect_mysql.php");
mysql_open();
不行啊,还是点击提交后,就打开insert.php,没有执行插入操作。。。

就打开insert.php 是什么意思?

楼主确认php环境没问题???

没看见楼主的提交按钮有onclick事件啊?

哎 看了那么多人的代码,还是lz的最好理解!!!!

就打开insert.php 是什么意思?
打开的意思就是,会用系统默认的php文件编辑器打开insert.php,例如,我这默认使用Emeditor打开。。。。。。

php环境配好了没有,文件有没有放入web服务器根目录下,怎么访问的?

php环境配好了没有,文件有没有放入web服务器根目录下,怎么访问的?
php环境配置应该没问题,我用的是eclipse_php,文件放在D:\Program Files\Apache Software Foundation\Apache2.2\htdocs\TestInsert(TestInsert是工程名),然后访问http://localhost/TestInsert/Page.html填写数据后,点击提交,弹出一个http://localhost/TestInsert/insert.php页面,但是数据库里面什么都没变啊。


就打开insert.php 是什么意思?
打开的意思就是,会用系统默认的php文件编辑器打开insert.php,例如,我这默认使用Emeditor打开。。。。。。
这个说错了,无视吧,应该是弹出一个http://localhost/TestInsert/insert.php页面,IE打开的

弹出下载页面说明php环境没有搭配成功

弹出下载页面说明php环境没有搭配成功
我觉得应该不是环境的问题,如果我直接把插入语句写在一个php中(值直接写好),是可以插入数据到数据库的,但是这种从页面获取的就不行。

弹出下载页面说明php环境没有搭配成功
而且我检查过了,PHP5,Mysql,Apache以及eclipse的安装,没看出啥问题。。。

,问题出现在链接数据库上,
链接数据库函数有问题,注释掉下面的函数部分就可以直接执行了!
//function mysql_open()
//{
$mysql_servername="localhost"; //
$mysql_username="root";
$mysql_password="11111";
$mysql_dbname="new";

$conn=mysql_connect($mysql_servername ,$mysql_username ,$mysql_password);
mysql_query("set names UTF8"); //UTF8
mysql_select_db($mysql_dbname , $conn);
// return $conn;
//}

,问题出现在链接数据库上,
链接数据库函数有问题,注释掉下面的函数部分就可以直接执行了!
//function mysql_open()
//{
$mysql_servername="localhost"; //
$mysql_username="root";
$mysql_password="11111";
$mysql_dbname="new";

$conn=mysql_connect($mysql_servername ,$mysql_username ,$mysql_password);
mysql_query("set names UTF8"); //UTF8
mysql_select_db($mysql_dbname , $conn);
// return $conn;
//}
你这个方法跟1楼是一样的,不是这个问题。

<?php$con = mysql_connect("localhost","root","11111");if (!$con)  {  die('Could not connect: ' . mysql_error());  }mysql_select_db("new", $con);$sql1 = "select max(id) from new";if(!mysql_query($sql1)){	die('Error: '.mysql_error());}$result = mysql_query($sql1);$id = mysqli_fetch_assoc($result);$sql="INSERT INTO new (id,title, content, time, news_cate_id)VALUES('".$id."','".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";//('2','".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";//将ID直接写成2可以更新,但我想实现自动根据数据库中最大ID(如果有更好的办法请大家说一下)更新//但是这里得到的ID却不是“1”“2”这样的值,谁知道怎么回事。if (!mysql_query($sql,$con))  {  die('Error: ' . mysql_error());  }echo "1 record added";//mysql_close($con)//$q = "insert into new (title,content,time,news_cate_id) values('".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";//mysql_query($q);//if(mysql_affected_rows()>0) echo "xinwentianjiachenggong!";?><hr /><a href="Page.html" target="win">fanhuijixutianjiaxinwen</a>
Copy after login


我将代码改成上面的样子通过错误信息发现是因为Id字段没有填导致插入失败,上面注释的部分还有问题。希望大家多帮忙,如果大家觉得分数不够我可以追加,只是觉得再开帖子麻烦了。

$result = mysql_query($sql1);
这样得到的result也不是数据库中存的1、2、3这样的值,然后导致更新失败,提示Error: Incorrect integer value: '' for column 'id' at row 1,想问问大家怎么样才能通过查询得到正确的id,或者result值然后插入数据库呢。

如果 id 是主键,那么因为主键不能重复,你向其赋 max(id) 显然是不对的!应为 max(id) + 1
如果 id 是主键,且是自增的,那么就无需向 id 赋值
如果 id 不是主键,但不允许为空,那么不向 id 赋值就是错误的

其实只要打印出 mysql_error() 的结果,就一切明了了

$id = mysql i_fetch_assoc($result); //连接用mysql,这里又用mysqli,肯定要错了,且返回的是一个数组
至少需要这样

$sql="INSERT INTO new (id,title, content, time, news_cate_id)
VALUES
('".$id['max(id)']."','".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";

如果你的id是主键,插入同一个id是会出错的。

如果 id 是主键,那么因为主键不能重复,你向其赋 max(id) 显然是不对的!应为 max(id) + 1
如果 id 是主键,且是自增的,那么就无需向 id 赋值
如果 id 不是主键,但不允许为空,那么不向 id 赋值就是错误的

其实只要打印出 mysql_error() 的结果,就一切明了了
如果 id 是主键,那么因为主键不能重复,你向其赋 max(id) 显然是不对的!应为 max(id) + 1这个我知道,只不过上面写得吧$id++;那句漏掉了。
id是主键,怎么设置主键自增啊。是不是在建表的时候哪里能设置啊?

我数据库的sql如下,哪里不对么?

/*Navicat MySQL Data TransferSource Server         : testSource Server Version : 50153Source Host           : localhost:3306Source Database       : newTarget Server Type    : MYSQLTarget Server Version : 50153File Encoding         : 65001Date: 2013-06-04 14:21:53*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `new`-- ----------------------------DROP TABLE IF EXISTS `new`;CREATE TABLE `new` (  `id` int(11) NOT NULL,  `title` varchar(50) DEFAULT NULL,  `content` varchar(100) DEFAULT NULL,  `time` datetime DEFAULT NULL,  `news_cate_id` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of new-- ----------------------------INSERT INTO `new` VALUES ('1', '111', '111', '2013-06-04 09:40:29', '1');INSERT INTO `new` VALUES ('2', 'eee', 'eeee', '2013-06-04 13:28:20', '1');
Copy after login

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
这样的话主键就自增了对吧,但是上面对应的
$sql="INSERT INTO new (id,title, content, time, news_cate_id)
VALUES
('".$id."','".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";
这部分应该怎么对应改动呢

$sql="INSERT INTO new (title, content, time, news_cate_id)
VALUES
('".$_POST["title"]."','".$_POST["content"]."',now(),".$_POST["c_id"].")";

知道了,只需要改成最初的样子就可以了,谢谢大家结贴了,结贴之前先追加点分数,以表示感谢

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles