Lazy Man's Logging:
<?php
/// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
/// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
///
/// @returns TRUE on success or FALSE on failure.
///
/// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
/// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
if($host)
mysql_connect($host, $user, $pass);
if($database)
mysql_select_db($database);
$qry = "CREATE TABLE IF NOT EXISTS `$table` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`when` TIMESTAMP DEFAULT NOW(),
`message` TEXT NOT NULL
);";
$result = mysql_query($qry);
if($result === FALSE)
return FALSE;
$qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";
$result = mysql_query($qry);
if($result === FALSE)
return FALSE;
return TRUE;
}
?>
MySQL 函数
简介
可以使用本类函数访问 MySQL 数据库服务器。有关 MySQL 的详细信息可以到 » http://www.mysql.com/ 查询。
MySQL 的文档可以在 » http://dev.mysql.com/doc/ 找到。
需求
为了能够顺利的使用本类函数,必须在编译 PHP 的时候添加 MySQL 的支持。
安装
编译时,只要使用 --with-mysql[=DIR] 配置选项即可,其中可选的 [DIR] 指向 MySQL 的安装目录。
虽然本 MySQL 扩展库兼容 MySQL 4.1.0 及其以后版本,但是它不支持这些版本提供的额外功能。要使用这些功能,请使用 MySQLi 扩展库。
如果要同时安装 mysql 扩展库和 mysqli 扩展库,必须使用同一个客户端库以避免任何冲突。
在 Linux 系统下安装
PHP 4
默认开启了 --with-mysql 选项。此默认行为可以用 --without-mysql 配置选项来禁止。如果启用 MySQL 而不指定安装目录的话,PHP 将使用绑定的 MySQL 客户端连接库。
还有其它应用程序使用 MySQL(例如 auth-mysql)的用户不要用绑定的库,而要指定 MySQL 的安装目录,如这样:--with-mysql=/path/to/mysql。这将强制 PHP 使用随 MySQL 安装的客户端连接库,就可以避免任何冲突。
在 Windows 系统下安装
PHP 4
PHP MySQL 扩展已经编译入 PHP。
PHP 5+
MySQL 默认未启用,因此必须在 php.ini 中激活 php_mysql.dll 动态连接库。此外,PHP 还需要访问 MySQL 客户端连接库。PHP 的 Windows 发行版包括了一个 libmysql.dll,为了让 PHP 能和 MySQL 对话,此文件必须放在 Windows 的系统路径 PATH 中。怎样做见 FAQ 中的“怎样把 PHP 目录加入到 Windows 路径中”。尽管将 libmysql.dll 拷贝到 Windows 系统目录中也可以(因为系统目录默认在系统路径 PATH 中),但不推荐这样做。
要激活任何 PHP 扩展库(例如 php_mysql.dll),PHP 指令 extension_dir 要被设为 PHP 扩展库所在的目录。参见手工 Windows 安装指南。PHP 5 下 extension_dir 取值的一个例子是 c:\php\ext。
Note: 如果启动 web 服务器时出现类似如下的错误:"Unable to load dynamic library './php_mysql.dll'",这是因为系统找不到 php_mysql.dll 和/或 libmysql.dll。
MySQL 安装注意事项
当同时加在本扩展库和 recode 扩展库时 PHP 可能会崩溃。更多信息见 recode 扩展库。
Note: 如果需要不同于 latin(默认值)的字符集,必须安装外部的(非绑定的)已编译入所需字符集支持的 libmysql。
运行时配置
这些函数的行为受 php.ini 的影响。
| 选项名称 | 默认值 | 可修改范围 | 更新记录 |
|---|---|---|---|
| mysql.allow_persistent | "1" | PHP_INI_SYSTEM | |
| mysql.max_persistent | "-1" | PHP_INI_SYSTEM | |
| mysql.max_links | "-1" | PHP_INI_SYSTEM | |
| mysql.trace_mode | "0" | PHP_INI_ALL | 自 PHP 4.3.0 起可用 |
| mysql.default_port | NULL | PHP_INI_ALL | |
| mysql.default_socket | NULL | PHP_INI_ALL | 自 PHP 4.0.1 起可用 |
| mysql.default_host | NULL | PHP_INI_ALL | |
| mysql.default_user | NULL | PHP_INI_ALL | |
| mysql.default_password | NULL | PHP_INI_ALL | |
| mysql.connect_timeout | "60" | PHP_INI_ALL | 自 PHP 4.3.0 起可用。在 PHP <= 4.3.2 时为 PHP_INI_SYSTEM |
以下是配置选项的简要解释。
- mysql.allow_persistent boolean
-
是否允许 MySQL 的持久连接。
- mysql.max_persistent integer
-
每个进程中最大的持久连接数目。
- mysql.max_links integer
-
每个进程中最大的连接数,包括持久连接。
- mysql.trace_mode boolean
-
跟踪模式。当激活 mysql.trace_mode 时,将会显示 table/index 扫描的警告,未释放的结果集以及 SQL 错误。(PHP 4.3.0 引进)
- mysql.default_port string
-
指定默认连接数据库的 TCP 端口号。如果没有指定默认端口号,则按顺序从 MYSQL_TCP_PORT 环境变量,/etc/services 文件中的 mysql-tcp 项或者编译时指定的 MYSQL_PORT 常量中取得。Win32 环境下只会使用 MYSQL_PORT 常量。
- mysql.default_socket string
-
当使用本地连接的时候,默认的 socket 名称。
- mysql.default_host string
-
默认连接的数据库服务器地址。不适用于 SQL 安全模式。
- mysql.default_user string
-
默认连接数据库时使用的用户名。不适用于 SQL 安全模式。
- mysql.default_password string
-
默认连接数据库时使用的密码。不适用于 SQL 安全模式。
- mysql.connect_timeout integer
-
连接超时秒数。在 Linux 中,此参数设定了等候来自服务器的响应的时长。
资源类型
在 MySQL 模块中使用了两种资源类型。第一种是数据库的连接句柄,第二种是 SQL 查询返回的结果集。
预定义常量
以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。
在 PHP 4.3.0 以后的版本中,允许在 mysql_connect() 函数和 mysql_pconnect() 函数中指定更多的客户端标记。下面列出所定义的常量:
| 常量 | 说明 |
|---|---|
| MYSQL_CLIENT_COMPRESS | 使用压缩的通讯协议 |
| MYSQL_CLIENT_IGNORE_SPACE | 允许在函数名后留空格位 |
| MYSQL_CLIENT_INTERACTIVE | 允许设置断开连接之前所空闲等候的 interactive_timeout 时间(代替 wait_timeout)。 |
| MYSQL_CLIENT_SSL | 使用 SSL 加密。本标志仅在 MySQL 客户端库版本为 4.x 或更高版本时可用。在 PHP 4 和 Windows 版的 PHP 5 安装包中绑定的都是 3.23.x。 |
mysql_fetch_array() 函数使用一个常量来表示所返回数组的类型。下面是常量的定义:
| 常量 | 说明 |
|---|---|
| MYSQL_ASSOC | 返回的数据列使用字段名作为数组的索引名。 |
| MYSQL_BOTH | 返回的数据列使用字段名及数字索引作为数组的索引名。 |
| MYSQL_NUM | 返回的数据列使用数字索引作为数组的索引名。索引从 0 开始,表示返回结果的第一个字段。 |
注释
Note: 大多数 MySQL 函数都接受 link_identifier 作为最后一个可选参数。如果未提供此参数,则使用最后一个打开的连接。如果不存在连接,则会用 php.ini 中定义的默认参数去尝试建立连接。如果连接不成功,函数返回 FALSE。
范例
下面的简单例子演示如何连接数据库,执行查询语句,打印返回结果集和断开数据库等一系列基本的 MySQL 操作。
Example#1 MySQL 例子
<?php
// 连接,选择数据库
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// 执行 SQL 查询
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// 用 HTML 显示结果
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// 释放结果集
mysql_free_result($result);
// 关闭连接
mysql_close($link);
?>
Table of Contents
- mysql_affected_rows — 取得前一次 MySQL 操作所影响的记录行数
- mysql_change_user — 改变活动连接中登录的用户
- mysql_client_encoding — 返回字符集的名称
- mysql_close — 关闭 MySQL 连接
- mysql_connect — 打开一个到 MySQL 服务器的连接
- mysql_create_db — 新建一个 MySQL 数据库
- mysql_data_seek — 移动内部结果的指针
- mysql_db_name — 取得结果数据
- mysql_db_query — 发送一条 MySQL 查询
- mysql_drop_db — 丢弃(删除)一个 MySQL 数据库
- mysql_errno — 返回上一个 MySQL 操作中的错误信息的数字编码
- mysql_error — 返回上一个 MySQL 操作产生的文本错误信息
- mysql_escape_string — 转义一个字符串用于 mysql_query
- mysql_fetch_array — 从结果集中取得一行作为关联数组,或数字数组,或二者兼有
- mysql_fetch_assoc — 从结果集中取得一行作为关联数组
- mysql_fetch_field — 从结果集中取得列信息并作为对象返回
- mysql_fetch_lengths — 取得结果集中每个输出的长度
- mysql_fetch_object — 从结果集中取得一行作为对象
- mysql_fetch_row — 从结果集中取得一行作为枚举数组
- mysql_field_flags — 从结果中取得和指定字段关联的标志
- mysql_field_len — 返回指定字段的长度
- mysql_field_name — 取得结果中指定字段的字段名
- mysql_field_seek — 将结果集中的指针设定为制定的字段偏移量
- mysql_field_table — 取得指定字段所在的表名
- mysql_field_type — 取得结果集中指定字段的类型
- mysql_free_result — 释放结果内存
- mysql_get_client_info — 取得 MySQL 客户端信息
- mysql_get_host_info — 取得 MySQL 主机信息
- mysql_get_proto_info — 取得 MySQL 协议信息
- mysql_get_server_info — 取得 MySQL 服务器信息
- mysql_info — 取得最近一条查询的信息
- mysql_insert_id — 取得上一步 INSERT 操作产生的 ID
- mysql_list_dbs — 列出 MySQL 服务器中所有的数据库
- mysql_list_fields — 列出 MySQL 结果中的字段
- mysql_list_processes — 列出 MySQL 进程
- mysql_list_tables — 列出 MySQL 数据库中的表
- mysql_num_fields — 取得结果集中字段的数目
- mysql_num_rows — 取得结果集中行的数目
- mysql_pconnect — 打开一个到 MySQL 服务器的持久连接
- mysql_ping — Ping 一个服务器连接,如果没有连接则重新连接
- mysql_query — 发送一条 MySQL 查询
- mysql_real_escape_string — 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集
- mysql_result — 取得结果数据
- mysql_select_db — 选择 MySQL 数据库
- mysql_set_charset — Sets the client character set
- mysql_stat — 取得当前系统状态
- mysql_tablename — 取得表名
- mysql_thread_id — 返回当前线程的 ID
- mysql_unbuffered_query — 向 MySQL 发送一条 SQL 查询,并不获取和缓存结果的行
MySQL
17-May-2008 05:28
05-Feb-2008 03:03
<?php
# Created by dhirendra can be reached at dhirendrak at yahoo dot com
# This script is created to check the data difference between two tables
# when the structure of both tables are same.
# Limitation :
# 1) Structure of both tables should be same.
# 2) Name of both table should be different but if same than obviously
# second table should be if different database.
# 3) If use two database than both database permission should be same
# as i am using aliases to get the information.
#
# USES::
# 1) This may be useful when you did some changes in your existing
# script and you expect the certain output. So with the help of this
# function you may compare the impact due to your changes in script.
#
#
$host=""; # host name or ip address
$user=""; # database user name
$pass=""; # database password
$database=""; # dateabase name with which you want to connect
# get connection with mysql
$dblink = @mysql_connect($host,$user,$pass);
# select and open database
mysql_select_db($database,$dblink);
$db1="< your db1 >"; // first database
// second database if database are same for both tables than use the same as db1
$db2="< your db2 >";
$table1="< your table1 >"; // first table
// second table if database is same for both tables than table name
# must be different but fields name are same and order of the fields are same.
$table2="< your table2 >";
// function starts here
function table_data_difference($first,$second)
{
global $dblink;
$sql1 = "SHOW FIELDS FROM $first";
$result = mysql_query($sql1,$dblink) or die("Having error in execution 1 ==".mysql_error());
while($row = mysql_fetch_object($result))
{
$from_fields[]=$row->Field;
}
$sql="select * from $first";
$res=mysql_query($sql,$dblink) or die("Having error in execution 2==".mysql_error());
$j=1;
while($row=mysql_fetch_array($res))
{
$num=count($from_fields);
$sql_next="select $second.* from $second where";
for($i=0;$i < $num;$i++)
{
$sql_next=$sql_next." ".$second.".".$from_fields[$i]."='".$row[$from_fields[$i]]."' and ";
}
$sql_next=substr($sql_next,0,strlen($sql_next)-5);
$res_next=mysql_query($sql_next,$dblink) or die("Having error in execution 3==".mysql_error());
$num1=mysql_num_rows($res_next);
if($num1==0)
{
for($i=0;$i < count($from_fields);$i++)
{
$val=$val."<br>".$from_fields[$i]."=".$row[$from_fields[$i]];
}
// Display the record which are not matched.
echo "<br>\n".$j.".".$val;
echo "<br>-----------------------------------------------------";
$j++;
}
}
}
$first=$db1.'.'.$table1;
$second=$db2.'.'.$table2;
table_data_difference($first,$second);
?>
18-Nov-2007 12:26
David:
In this line:
$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";
PHP may read $username[, *including* the open square bracket, and may think you are trying to get into an array.
You should use this instead:
$query = "SELECT username FROM users WHERE username REGEXP '${username}[0-9*]'";
Or maybe this:
$query = "SELECT username FROM users WHERE username REGEXP '$username" . "[0-9*]'";
10-Nov-2007 12:13
I am wanting to increment usernames which are to be alphabetic characters A-Z or a-z and if someone uses "abc" it will automatically be given "abc1" and the next applicant to apply for that same username will automatically be given "abc2", the next "abc3" and so on. If I enter the following into MySQL;
SELECT username FROM users WHERE username REGEXP 'abc[0-9*]';
the result is
abc1
abc2
abc3
I have been given the following script from another forum but it does not work;
<?php
$username = 'abc';
$query = "SELECT username FROM users WHERE username LIKE '$username%'";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)) {
$n = str_replace($username, '', $row['username']);
if ($old_n+1!=$n) {
$new_user = $username . ($old_n+1);
break;
}
}
?>
In addition to the script not working the "LIKE" function would not be suitable because if a username was applied as "blue" it would pick up usernames "blue1" and "bluebird1" therefore it appears as if "REGEXP '$username[0-9*]' is the only or correct option.
I have tried the REGEXP option in association with the balance of the code but it appears as if PHP will not interact with the "[" and "]" in the following;
$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";
07-Nov-2007 08:33
<?php
/*
MySQL (Community) Server Installation on 32-bit Windows XP running Apache
On Windows, the recommended way to run MySQL is to install it as a Windows service, whereby MySQL starts and stops automatically when Windows starts and stops. A MySQL server installed as a service can also be controlled from the command line commands, or with the graphical Services utility like phpMyAdmin.
PHP ---> MySQL CONNECTORS (php_mysql.dll and php_mysqli.dll as extensions)
MySQL provides the mysql and mysqli extensions for the Windows operating system on http://dev.mysql.com/downloads/connector/php/ for MySQL version 4.1.16 and higher, MySQL 5.0.18, and MySQL 5.1. As with enabling any PHP extension in php.ini (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located.
MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.
Following PHP Script is useful to test PHP connection with MySQL.
*/
//$connect = mysql_connect("Your Host Name", "MySQL root directory", 'MySQL password, if any');
//$connect = mysql_connect("Host Name or Address - 127.0.0.1", "root", 'password');
$connect = mysql_connect("localhost", "root", 'password');
if ($connect){
echo "Congratulations!\n<br>";
echo "Successfully connected to MySQL database server.\n<br>";
}else{
$error = mysql_error();
echo "Could not connect to the database. Error = $error.\n<br>";
exit();
}
// Closing connection
$close = mysql_close($connect);
if ($close){
echo "\n<br>";
echo "Now closing the connection...\n<br>";
echo "MySQL connection closed successfully as well.\n<br>";
}else{
echo "There's a problem in closing MySQL connection.\n<br>";
}
exit();
?>
15-Oct-2007 03:01
@Amanda 12-Oct-2007 09:58
I almost had to ask myself if this was a real question... If the MySQL server rejects the connection attempt then, yes, MySQL would be able to send back an error to PHP... And if PHP can't access the target MySQL server at all then it is also smart enough to issue the appropriate error all by itself...
13-Oct-2007 09:36
Also, to secure MySQL data and to be able to comply with PCI standards, you should encrypt the data. There are many ways to do it. For hackers, you can use dm-crypt (www.saout.de/misc/dm-crypt) tool. It is basically used to encrypt the whole partition. If you want a sophisticated solution go with Security-GENERAL for MySQL from packet general (www.packetgeneral.com)
On windows, you can use disk encryption feature provided by windows itself or tool like trucrypt (www.truecrypt.org)
02-Sep-2007 06:19
On 11-Apr-2007 admin at mihalism dot com posted an 'easy to use MySql-class'.
In my opinion there is a bug in the get_affected_rows-function. It refers to query-id, but it should refer to connect-id instead.
The corrected function should be:
function get_affected_rows($connect_id = ""){
if($connect_id == NULL){
$return = mysql_affected_rows($this->connect_id);
}else{
$return = mysql_affected_rows($connect_id);
}
if(!$return){
$this->error();
}else{
return $return;
}
}
14-Jun-2007 11:56
After finally getting IIS, PHP, and MySQL on a new Windows XP machine, I decided to write the steps I took so you can see how it was done: http://www.atksolutions.com/articles/install_php_mysql_iis.html
Hope this helps.
16-Apr-2007 07:14
Correct algorithm to generate MySQL password hash is:
<?php
function mysql_password($passStr) {
$nr=0x50305735;
$nr2=0x12345671;
$add=7;
$charArr = preg_split("//", $passStr);
foreach ($charArr as $char) {
if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
$charVal = ord($char);
$nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
$nr &= 0x7fffffff;
$nr2 += ($nr2 << 8) ^ $nr;
$nr2 &= 0x7fffffff;
$add += $charVal;
}
return sprintf("%08x%08x", $nr, $nr2);
}
?>
15-Apr-2007 02:20
This PHP5-only class is used so that $db isn't passed. Kudos to arjen at queek dot nl for example.
<?php
class SQL {
private $db;
public function __construct($host="localhost",$user="root",$pass="",$db="") {
$this->db = @mysql_connect($host, $user, $pass);
if(!$this->db) die(@mysql_error());
if($db != "") $dbs = @mysql_select_db($db);
if(!$dbs) die(@mysql_error());
}
public function __destruct() {
@mysql_close($db);
}
public function __call($function, $arguments) {
array_push($arguments, $this->db);
$return = call_user_func_array("mysql_".$function, $arguments);
if(!$return) die(@mysql_error());
}
}
$db = new SQL();
$query = $db->query("SELECT * FROM this_table WHERE my_variable='1'");
$fetch = $db->fetch_array($query);
print_r($fetch);
?>
13-Apr-2007 05:35
For Windows users, please note:
If apache is installed as a service, and you change PATH variable so it can reach libmysql.dll, you will need to reboot your machine in order to have changes applied.
11-Apr-2007 10:48
Heres a easy to use MySQL class for any website
<?php
class mysql_db{
//+======================================================+
function sql_connect($sqlserver, $sqluser, $sqlpassword, $database){
$this->connect_id = mysql_connect($sqlserver, $sqluser, $sqlpassword);
if($this->connect_id){
if (mysql_select_db($database)){
return $this->connect_id;
}else{
return $this->error();
}
}else{
return $this->error();
}
}
//+======================================================+
function error(){
if(mysql_error() != ''){
echo '<b>MySQL Error</b>: '.mysql_error().'<br/>';
}
}
//+======================================================+
function query($query){
if ($query != NULL){
$this->query_result = mysql_query($query, $this->connect_id);
if(!$this->query_result){
return $this->error();
}else{
return $this->query_result;
}
}else{
return '<b>MySQL Error</b>: Empty Query!';
}
}
//+======================================================+
function get_num_rows($query_id = ""){
if($query_id == NULL){
$return = mysql_num_rows($this->query_result);
}else{
$return = mysql_num_rows($query_id);
}
if(!$return){
$this->error();
}else{
return $return;
}
}
//+======================================================+
function fetch_row($query_id = ""){
if($query_id == NULL){
$return = mysql_fetch_array($this->query_result);
}else{
$return = mysql_fetch_array($query_id);
}
if(!$return){
$this->error();
}else{
return $return;
}
}
//+======================================================+
function get_affected_rows($query_id = ""){
if($query_id == NULL){
$return = mysql_affected_rows($this->query_result);
}else{
$return = mysql_affected_rows($query_id);
}
if(!$return){
$this->error();
}else{
return $return;
}
}
//+======================================================+
function sql_close(){
if($this->connect_id){
return mysql_close($this->connect_id);
}
}
//+======================================================+
}
/* Example */
$DB = new mysql_db();
$DB->sql_connect('sql_host', 'sql_user', 'sql_password', 'sql_database_name');
$DB->query("SELECT * FROM `members`");
$DB->sql_close();
?>
Note, that the sql.safe_mode configuration setting does effect all mysql_* functions. This has nothing to to with the php safe mode, check the [SQL] section in php.ini.
I found out, that if you set sql.safe_mode = On, mysql_connect will ignore provided username and passwort and makes use of the script owner instead (checked on debian).
28-Nov-2006 06:37
I was working with a friend of mine and he happened wanted to sort data based on the column names, well this function will basically sort the Field Names in ABC order and then from there on it'll add the data based on the field names assigned to...
You can use this to create easily forms and exclude what you don't want to be as entered data or sort it based on what order you want...
<?php
/*
* By Benjamin Willard (c) 2006
*
* Sorts a Field by the Column Name (in ABC Order)
*
* @param string : Table Name of where to Display the Values
* @param integer : Database Link
* (Optional) @param array : This will sort whatever you wish to be displayed on the top of the list
* (Optional) @param array : This will exclude what you do not want displayed
*
* return @param array : Returns an Array of the Column Data
* [Usage]
* mysql_sort_field_column( string tablename, int database_link [, array sortfirst, array exclude] )
* [Example]
* $array = mysql_sort_field_column( "test", $c, array( "id", "name" ), array( "password" ) );
*
* [Output]
* Array
* (
* [0] => id
* [Field] => id
* [1] => int(11)
* [Type] => int(11)
* [2] =>
* [Null] =>
* [3] => PRI
* [Key] => PRI
* [4] =>
* [Default] =>
* [5] => auto_increment
* [Extra] => auto_increment
* )
* [id] => 1;
*
*/
function mysql_sort_field_column( $tablename, $link, $sortfirst = '', $exclude = '' )
{
$show=mysql_query("SHOW COLUMNS FROM $tablename", $link);
$array=array();
while( $fetch = mysql_fetch_array($show ) )
{
$array[$fetch['Field']] = $fetch;
}
ksort($array);
if( $sortfirst )
{
if( is_array($sortfirst) )
{
$newarray = array();
foreach( $sortfirst AS $i2 => $v )
$newarray[$v] = $array[$v];
foreach( $array AS $index => $val2 )
{
if( in_array($index, $sortfirst ) )
continue;
$newarray[$index] = $val2;
}
$array = $newarray;
}
}
if( $exclude )
{
if( is_array($exclude) )
{
$out = array();
foreach( $array AS $index2 => $val2 )
{
if( in_array( $index2, $exclude ) )
continue;
$out[$index2] = $val2;
}
$array = $out;
}
}
return $array;
}
?>
20-Oct-2006 02:00
In response to martijn at elicit dot nl
Actually it is possible as a query, even with an auto_increment key field. Like so...
INSERT
INTO
tablename
( list, of, ALL, similar, columns )
( SELECT
*
FROM
tablename
WHERE
somefield = 'somevalue' )
That should work.
29-Aug-2006 03:52
Keeping history records usually requires you to duplicate rows. With standard MySQL syntax you can create a query like this:
INSERT
INTO
tablename
SELECT
*
FROM
tablename
WHERE
somefield = 'somevalue'
The problem is that this won't work if you are using an auto_numbering key id field. There is no way to do this with standard MySQL syntax and I haven't been able to find a standard php function as well. So here's the function I wrote for that very purpose:
<?php
// function to create a duplicate record in a table with 1 auto_increment id.
function mysql_duplicate_record($table, $id_field, $id)
{
// load original record into array
$query = 'SELECT * FROM ' . $table . ' WHERE ' . $id_field . ' = ' . $id . ' LIMIT 1;';
$r = mysql_query( $query ) or die('Error, query failed. ' . mysql_error());
$ar = mysql_fetch_array( $r, MYSQL_ASSOC );
// insert new record and get new auto_increment id
mysql_query ('LOCK TABLES ' . $table . ' WRITE;') or die('Error, query failed. ' . mysql_error());
mysql_query ('INSERT INTO ' . $table . ' ( `' . $id_field . '` ) VALUES ( NULL );') or die('Error, query failed. ' . mysql_error());
$id = mysql_insert_id();
mysql_query ('UNLOCK TABLES;') or die('Error, query failed. ' . mysql_error());
// update new record with values from previous record
$query = 'UPDATE ' . $table . ' SET ';
while ($value = current($ar))
{
if (key($ar) != $id_field)
{
$query .= '`'.key($ar).'` = "'.$value.'", ';
}
next($ar);
}
$query = substr($query,0,strlen($query)-2).' ';
$query .= 'WHERE ' . $id_field . ' = "' . $id . '" LIMIT 1;';
mysql_query($query) or die('Error, query failed. ' . mysql_error());
// return the new id
return $id;
}
?>
14-Aug-2006 06:32
I made this function to reduce DB calls. You can store Mysql results in a session var and sort the results on any column. Might work nice in an AJAX app.
<?
function mysql_sort($results, $sort_field, $dir="ASC") {
$temp_array = array();
$i=0;
foreach ($results as $res) {
$temp_array[$i] = $res[$sort_field];
$i++;
}
if ($dir=="ASC") {
asort($temp_array);
} else {
arsort($temp_array);
}
$new_results = array();
$i=0;
foreach($temp_array as $k => $v) {
$new_results[$i] = $results[$k];
$i++;
}
ksort($new_results);
return $new_results;
}
//use
if (count($_SESSION["res"])==0) {
$_SESSION["res"] = [GET DATABASE RESULTS HOWEVER YOU MAY]
}
$_SESSION["res"] = mysql_sort($_SESSION["res"], $_REQUEST["sort"], $_REQUEST["dir"]);
?>
<table>
<tr>
<td><a href="page.php?sort=f_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">First</a></td>
<td><a href="page.php?sort=l_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">Last</a></td>
</tr>
<? foreach ($_SESSION["res"] as $r) {?>
<tr>
<td><?=$r["f_name"]?></td>
<td><?=$r["l_name"]?></td>
</tr>
<? } ?>
</table>
20-Jul-2006 07:58
In response to Conrad Decker's post below:
If your tables contain foreign key constraints you will not be able to properly restore from a datafile created by mysqldump.
mysqldump dumps table data in alphabetical order, not in the logical order required by the foreign key constraints.
10-Jul-2006 02:27
I have recently ran into a problem with configuring php extensions related to mysql (namely, mysql and pdo_mysql). Later I've discovered that it wasn't a PHP problem but that of MySQL - libmysqlclient doesn't ship with binary downloads. I've built MySQL from sources and both extensions then compiled successfully.
24-May-2006 04:56
In regards to the previous post...you should actually be able to pipe a mysql dump directly back into mysql.
From the command line something like
mysql -u username -p databasename < mysqldumpfilename
should rebuild the database.
There are some additional options one can use, and I believe mysqldump from different versions of mysql may not be completely compatible.
02-May-2006 04:43
I'm in the process of changing web hosts and my previous host provided a "dump" of the database in the form of a sequence of SQL requests that (I assume) have to be executed in order to rebuild the database on another system. It was generated using "MySQL dump 9.11". Queries are finished by a semicolon and linefeed, while comment-lines begin with a double hyphen. The script below opens a connection to an SQL server and loads a dump file $file of this format into the database $dest_db.
function load_db_dump($file,$sqlserver,$user,$pass,$dest_db)
{
$sql=mysql_connect($sqlserver,$user,$pass);
mysql_select_db($dest_db);
$a=file($file);
foreach ($a as $n => $l) if (substr($l,0,2)=='--') unset($a[$n]);
$a=explode(";\n",implode("\n",$a));
unset($a[count($a)-1]);
foreach ($a as $q) if ($q)
if (!mysql_query($q)) {echo "Fail on '$q'"; mysql_close($sql); return 0;}
mysql_close($sql);
return 1;
}
This may not be watertight if the ";\n" sequence appears inside queries, but I hope it helps others who are in posession of such dumps.
20-Apr-2006 03:33
After configuring php.ini as outlined above (set the extension_dir variable and uncomment the appropriate mysql library) I kept receiving the following error on every Apache restart:
PHP Startup: Unable to load dynamic library './ext\\php_mysql.dll'
After trawling the web, most suggestions seemed to center on copying the libmysql.dll from the php install directory to c:\windows\system32. While this can work, it can also complicate future upgrades, since you'll always have to copy the new libmysql.dll to insure proper operation.
Instead, if you run a search for "libmysql.dll", you'll likely find several versions in various directories. After removing the older (smaller) versions from the other directories in my PATH, (c:\windows, c:\windows\system32) - and making sure the php install directory was in the PATH, apache/php was able to successfully locate the correct DLL and start without errors.
Hopefully someone will find this helpful. ;)
04-Apr-2006 01:42
Hi,
For all those who may still be struggling to get PHP to work with Windows and IIS, I finally found something that works.
If you are getting the error message that function mysql_connect could not be found and you're sure you enabled php_mysql in php.ini this is what finally solved my problem.
The post from mmw_canada at yahoo dot com on 10-Jul-2005 06:15 pointed me in the right direction. Thanks mmw_canada!
1.) If you are connected to your Windows box via Remote Desktop, there is a switch to Remote Desktop that will connect you to the console session. This is important because when IIS starts up, it's error messages go to the console. If you are sitting at the physical machine, you can ignore this step.
Here is the command
mstsc -v:10.192.186.xxx /F -console
For a more complete list of supported commands, type this at a dos command window:
mstsc /?
2.) Add a registry entry that tells PHP where to find its php.ini file. Copy the following text and paste it in a text file. Rename the text file to something like phpini.reg and double-click it to add it to your registry.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\\SOFTWARE\\PHP]
"IniFilePath"="C:\\\\PHP"
2.) Add c:\\php; (or wherever you unzipped PHP to) to your environment variable "Path". Here is the important part that caused me hours and hours of grief. When adding c:\\php; to the PATH environment variable, make SURE you add it BEFORE the path to CVSNT or MYSQL. PHP, CVSNT, and MYSQL all have a file called libmysql.dll. Search order is important for PHP to find its file libmysql.dll first. PHP must come first in the search path. Otherwise you will get an error from the DLL on the console screen when IIS starts up saying it can't find the specified function call.
To see the order of your environment variables, open up a dos window and type "set" and press enter. Look at what Path is equal to. c:\\php; better come before cvsnt and mysql or it will never work properly.
Hope this helps!
01-Apr-2006 05:11
After tearing my eyes out in frustration, I've finally found a way to enable extensions that always works for me. It's pretty straightforward.
1. Download the latest zip-version of PHP.
2. Delete (or backup) the contents of your PHP folder (usually c:\php). (remember to save any ext's not included in the zip)
3. Copy everything in the zip-file into your PHP folder
4. Be sure that extension_dir is set to "./ext" in php.ini
5. Enable whichever extensions you want to use in php.ini
I guess that deleting everything is quite unnecessary, the important thing is that the php.exe and extensions in the same zip are of compatible versions. I've never found any need to change the PATH environment variable.
Hope it helps!
16-Mar-2006 06:08
when using Fedora Core linux Mysql rpm installation.
Configure as following to load the mysql header files.
./configure --with-mysql=/usr/
Remember to do make clean to remove old configurations before compile
17-Feb-2006 07:13
If you want to get PHP working nicely with MySQL, even with Apache, under Windows based systems, try XAMPP, from Apache Friends. It saves messing about with config files, which is the only major problem with trying to get the three to work together under windows.
http://www.apachefriends.org/en/xampp-windows.html
14-Feb-2006 08:29
php_mysql.dll and libmysql.dll for windows systems can be downloaded from http://dev.mysql.com/downloads/connector/php/
It can be useful to those who are using the PHP Windows installer, which does not have any external extensions included.
04-Feb-2006 01:20
Oops! Don't use that one, use this:
<?php
class database {
function database($server, $username, $password, $database) {
$this->connection = mysql_connect($server, $username, $password);
if (!$this->connection || !mysql_select_db($database, $this->connection)) {
return false;
} else {
return true;
}
}
function query($sql, $type = MYSQL_BOTH) {
$query = mysql_query($sql, $this->connection);
while ($row = mysql_fetch_row($query)) {
$return[] = $row;
}
return $return;
}
}
/* Change this to reflect your database setup */
$database = new database('localhost', 'root', '', 'forum');
if (!$database) {
exit('Could not connect to the database!');
}
?>
21-Dec-2005 04:12
For those of you on an OS that has older mysql libs and want to properly authenticate to the modern mysql versions, without the OLD_PASSWORD hack; compile php with where you have installed the latest mysql binary package:
./configure --with-mysql=/usr/local/mysql
if you have mysql installed on seperate server, just drop it into the target directory on what ever machine you are compiling it on.
Be sure to "make clean" before building or it may look in the previous place.
Use the output of mysql_get_client_info(); to test before and after.
16-Dec-2005 05:15
I've seen alot of newbies getting frustrated over the extenstions not being installed initially, so heres a quick tut for Windows.
It's ok to use the php5 installer. Just be sure to also grab the .zip or "manual" version of php5.
Install it like any other app. It's pretty straight forward. Don't forget to set the securities mentioned in the last message box at the end of the install. Next, If you installed php to c:\php then you will need to add this to your PATH environment variable. This is a very important step.
Now open up the .zip manual version of php5 and extract the ext folder, and "libmysql.dll" to "c:\php\".
You *MUST* set your security permissions on libmysql.dll and the ext folder to READ/READ&EXECUTE for IUSR_"MACHINE_NAME". like my machine is called master<acct = IUSR_MASTER>. If you don't do this you will recieve an ******.dll - Access Denied. type message.
Next edit your php.ini file usually located in c:\windows\.
Find the line for extension_dir variable and make it say
extension_dir = "c:\php\ext\"
Then scroll down a little bit and find the lines that say
;extension=php_mbstring.dll
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_dba.dll
;extension=php_dbase.dll
;extension=php_exif.dll
;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_ifx.dll
just remove the semicolin for each extension you would like loaded. Such as
extention=php_mysql.dll
and so on.
Now just reboot and all should be well. Query away. you basically only need to reboot to update the PATH environment variable. Hope this helps at least 1 person.:)
