Escolar Documentos
Profissional Documentos
Cultura Documentos
Notas
Note: Muchas funciones de MySQL aceptan link_identifier como ltimo parmetro. Si no se proviene, se utilizar la ltima conexin abierta. Si esta no existe, se intentar establecer conexin con el parmetro predeterminado definido en php.ini. Si no hay xito, las funciones devuelven FALSE
Table of Contents
mysql_affected_rows Obtiene el nmero de filas afectadas en la anterior operacin de MySQL mysql_client_encoding Devuelve el nombre de la coleccin de caracteres mysql_close Cierra la conexin de MySQL mysql_connect Abre una conexin al servidor MySQL mysql_create_db Crea una base de datos MySQL mysql_data_seek Mueve el apuntador interno del resultado mysql_db_name Obtiene los datos del resultado mysql_db_query Enva una consulta MySQL mysql_drop_db Omite (elimina) una base de datos MySQL mysql_errno Devuelve un mensaje de error con un valor numrico de la operacin anterior con MySQL mysql_error Devuelve el texto con error del mensaje de la anterior operacin MySQL mysql_escape_string Escapa una cadena para ser usada en mysql_query mysql_fetch_array Recupera una fila de resultado como un array asociativo, un array numrico o como ambos mysql_fetch_assoc Recupera una fila de resultado como un array asociativo mysql_fetch_field Obtiene la informacin de una columna desde un resultado y la devuelve como un objeto mysql_fetch_lengths Obtiene la longitud de cada salida en un resultado mysql_fetch_object Recupera una fila de resultado como un array objeto mysql_fetch_row Recupera una fila de resultado como un array numrico mysql_field_flags Obtiene los flags asociados con el campo especificado en un resultado mysql_field_len Devuelve la longitud del campo especificado mysql_field_name Obtiene el nombre del campo especificado en un resultado mysql_field_seek Establece el apuntador del resultado en un nmero de campo especficado mysql_field_table Obtiene el nombre de la tabla en la que est el campo especificado mysql_field_type Obtiene el tipo del campo especificado en un resultado mysql_free_result Libera la memoria del resultado mysql_get_client_info Obtener informacin del cliente MySQL mysql_get_host_info Obtener informacin de la mquina anfitriona MySQL
mysql_get_proto_info Obtener informacin del protocolo MySQL mysql_get_server_info Obtener informacin del servidor MySQL mysql_info Obtiene informacin sobre la consulta ms reciente mysql_insert_id Obtiene la ID generada en la ltima consulta mysql_list_dbs Lista de las bases de datos disponibles en un servidor MySQL mysql_list_fields Lista los campos del resultado de MySQL mysql_list_processes Lista los procesos MySQL mysql_list_tables Lista las tablas de una base de datos MySQL mysql_num_fields Obtiene el nmero de campos en un resultado mysql_num_rows Obtener el nmero de filas de un resultset mysql_pconnect Abre una conexin persistente a un servidor MySQL mysql_ping Efectuar un chequeo de respuesta (ping) sobre una conexin de servidor o reconectarse si no hay conexin mysql_query Enviar una consulta MySQL mysql_real_escape_string Escapa caracteres especiales en una cadena para ser usado en una sentencia SQL mysql_result Obtener datos de resultado mysql_select_db Seleccionar una base de datos MySQL mysql_set_charset Establece el conjunto de caracteres del cliente mysql_stat Obtiene el status actual del sistema mysql_tablename Obtiene el nombre de la tabla de un campo mysql_thread_id Devuelve el ID del hilo actual mysql_unbuffered_query Enva una consulta SQL a MySQL, sin recuperar ni colocar en bfer las filas de resultado
mysql_affected_rows
Last updated: Fri, 27 May 2011 Funciones de MySQL Vladimir Kosmala 27-Oct-2010 09:57
add a note User Contributed Notes Here a mysql helper containing the main functions of the mysql extension. It's easy to understand for a beginner and quite useful because queries are secure. It understands what you want, just write your sql query. I called it mysql_magic. <?php // Examples $nb_affected = mysql_magic('delete from users'); $nb = mysql_magic('select count(*) from users'); $one_row = mysql_magic('select * from users limit 1'); $all_rows = mysql_magic('select * from users where name = ?', 'John'); $id = mysql_magic('insert into users(name,rank) values(?,?)', 'Vincent', 3); ?> <?php // Usage: mysql_magic($query [, $arg...]); function mysql_magic() { global $dblink, $sqlhost, $sqluser, $sqlpass, $sqlbase;
$narg = func_num_args(); $args = func_get_args(); if (!$dblink) { $dblink = mysql_connect( $sqlhost, $sqluser, $sqlpass ); mysql_select_db( $sqlbase, $dblink ); } $req_sql = array_shift($args); $req_args = $args; $req_query = mysql_bind($req_sql, $req_args); $req_result = mysql_query($req_query); if (!$req_result) { trigger_error(mysql_error()); return false; } if (startsWith($req_sql, 'delete') || startsWith($req_sql, 'update')) { return mysql_affected_rows(); // -1 || N } else if (startsWith($req_sql, 'insert')) { return mysql_insert_id(); // ID || 0 || FALSE } else if (endsWith($req_sql, 'limit 1')) { return mysql_fetch_assoc($req_result); // [] || FALSE } else if (startsWith($req_sql, 'select count(*)')) { $line = mysql_fetch_row($req_result); return $line[0]; // N } else { return mysql_fetch_all($req_result); // [][] } } function mysql_bind($sql, $values=array()) { foreach ($values as &$value) $value = mysql_real_escape_string($value); $sql = vsprintf( str_replace('?', "'%s'", $sql), $values); return $sql; } function mysql_fetch_all($result) { $resultArray = array(); while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray)); return $resultArray; }
function startsWith($haystack,$needle,$case=false) { if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);} return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0); } function endsWith($haystack,$needle,$case=false) { if($case){return (strcmp(substr($haystack, strlen($haystack) strlen($needle)),$needle)===0);} return (strcasecmp(substr($haystack, strlen($haystack) strlen($needle)),$needle)===0); } ?> Don't forget to set $sqlhost, $sqluser, $sqlpass and $sqlbase. With help of : mysql_bind : http://php.net/manual/en/function.mysql-real-escapestring.php#96391 mysql_fetch_all : http://php.net/manual/en/function.mysql-fetchassoc.php#90030 trigger_error may be enhanced with this tip : http://php.net/manual/en/function.trigger-error.php#98910
} ?> MySQL has multiple timeout counters, one for inserts, and one for deletes, and I could not find a way to extend them in PHP. Please note that this is a different issue entirely than the 'connect' timeout. Every 15 seconds, this function will insert, select, and delete a row from the temporary table, thus preventing a query timeout. Good Luck!
# 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); ?>
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*]'";
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(); ?>
} //+======================================================+ 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(); ?>
26-Jan-2007 03:14
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).
<?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; } ?>
* 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; } ?>
$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>
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!
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!
yp 15-Mar-2006 04: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
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.
This is a small function I wrote to handle queries on a table. It can query a table, order and sort, and supports inner joins. This function also returns the result as a single row or all rows. Enjoy : <?php /** * Selects Fields from a database/table. * Also supports INNER JOINS, GROUP BY, ORDER BY. * * @Author : Jonathon Hibbard * * @param string $db_name //Name of Database * @param string $table //Name of Table * @param array $fields //Field Names we want to select * @param array $inner //Fields to be INNER JOINED * @param array $where //WHERE fields. * @param string $group_by //Field to group by. * @param string $order_by //Field to order by * @param string $asc //Asc or Desc order * @param string $return_array //Defines $rst as an array or single row * @return $rst //Returns the result * * @example : (1) getFields('mytool','master', * 'array('master.master_id','master.fname_id')); * (2) getFields('mytool','master', * 'array('master.master_id','master.fname_id', * 'fname.fname'), array(0=>array('mytool', * 'fname','master','fname_id',)), * 'master.default_value <> "", false); * (3) getFields('mytool','master','master.master_id',NULL, * 'master.fname_id = "3",NULL,NULL,NULL,false); */ function getFields($db_name=NULL,$table=NULL,$fields=NULL,$inner=NULL, $where=NULL,$group_by=NULL,$order_by=NULL,$asc=NULL, $return_array=true) { $C_NAME = __CLASS__."::".__FUNCTION__; $sql = "SELECT "; is_array($fields) ? $sql .= implode(',',$fields) : $sql .= $fields; $sql .= " FROM ".$db_name.".".$table; if(!empty($inner)) { $total_inners = count($inner); for($i=0; $i<$total_inners; $i++) $sql .= " INNER JOIN ".$inner[$i][0].".".$inner[$i][1]." ON ".$inner[$i][1].".".$inner[$i][2]." = ".$inner[$i][3].".".$inner[$i][2]; } if(!empty($where)) { is_array($where) ? $sql .= " WHERE ".implode(' AND ',$where) : die("Fatal Error : Variable must be an array.
Variable type is : ".gettype($where)); } !empty($group_by) ? $sql .= " GROUP BY ".$group_by : ''; !empty($order_by) ? $sql .= " ORDER BY ".$order_by : ''; !empty($asc) ? $sql .= " ".$asc : ''; $sql .= " # Query resides in ".__FILE__."->".$C_NAME." on line ".__LINE__; if($return_array === true) { $rst = mysql_query($sql) or die("An Error Has Occurred! \n MySQL Error Reports : ".mysql_error()." \n The Error Occured in ".__FILE__." -> ".$C_NAME); $i=0; while($row = mysql_fetch_assoc($rst)) { $rowRst[] = $row[$fields[$i]]; $i++; } } else { $rst = mysql_query($sql) or die("An Error Has Occurred! \n MySQL Error Reports : ".mysql_error()." \n The Error Occured in ".__FILE__." -> ".$C_NAME); $rowRst = mysql_fetch_assoc($rst); } return $rowRst; } ?>
3. extension=php_mysql.dll untill on phpinfo.php show MySQL Support enabled Active Persistent Links 0 Active Links 0 Client API version 4.1.12
`id_tipo_telefone` int(11) NOT NULL default '0', `numero` varchar(15) NOT NULL default '', `id_pessoa` int(11) NOT NULL default '0', PRIMARY KEY (`id`), KEY `id_tipo_telefone` (`id_tipo_telefone`), KEY `id_pessoa` (`id_pessoa`), CONSTRAINT `0_775` FOREIGN KEY (`id_tipo_telefone`) REFERENCES `tipos_telefone` (`id`), CONSTRAINT `0_776` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoas` (`id`) ) TYPE=InnoDB that returns $tbname = "telefones" $fields = array("numero"); $kfields = array("id_tipo_telefone","id_pessoa"); $tipos = array("varchar"); Hope it helps... <?php function parseQuery($Q, &$tbname, &$fields, &$kfields, &$tipos) { /** rules to a corect parse: * * 1 - primary key must be named "id" * 2 - foreign key must be named "id..." eg.: id_field * 3 - lowercase is recomended */ $Q = str_replace(array(chr(10),chr(13))," ",$Q); $Q = str_replace(array("'","`")," ",$Q); preg_match("/([^(]*)\((.*)\)(.*)/",$Q,$A); $part1 = $A[1]; $part2 = $A[2]; $part3 = $A[3]; preg_match("/(.*) ([a-zA-Z_]+)/",$part1,$A); $tbname = strtolower($A[2]); $temp = split(",",$part2); foreach ($temp as $t) { preg_match("/ *([a-zA-Z_]+) +([a-zA-Z_]+)(.*)/",$t,$A); $pcampo = strtolower($A[1]); $ptipo = strtolower($A[2]); if (!preg_match("/$pcampo/","primary key constraint id unique foreign") ) { if ( ($pcampo[0] == "i") && ($pcampo[1] == "d") ) $kfields[] = $pcampo; else { $fields[] = $pcampo; $tipos[] = $ptipo; } } } } ?>
with: ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php Action application/x-httpd-php "/php/php-cgi.exe" 2. Go to php directory c:\php then rename php.ini-dist to php.ini (or make a new php.ini based on old php.ini file), make sure we set the right extension: extension_dir = "c:\php\ext" extension=php_mysql.dll If you setup an php script that call function php_info(); and you can find table: MySQL Support enabled Active Persistent Links 0 Active Links 0 Client API version 4.1.7 that mean the mysql.dll properly attached to suppport the php, happy SQL-ing
there. I meant to include this in my note below, apologies for any confusion.
class mysql_array { public function __construct ( $s_host , $s_user , $s_pass , $s_db ) { $this -> r_conn = mysql_connect ( $s_host , $s_user , $s_pass ) or die ( mysql_error ( ) ) ; mysql_select_db ( $s_db ) ; } private function array_make ( $s_sql , $i_type ) { $r_rs = mysql_query ( $s_sql , $this -> r_conn ) or die ( mysql_error ( ) ) ; while ( $a_col = mysql_fetch_array ( $r_rs , $i_type ) ) { $a_rs [ ] = $a_col ; } mysql_free_result ( $r_rs ) ; return ( $a_rs ) ; } public function array_logic ( $s_sql ) { $a_rs = $this -> array_make ( $s_sql , MYSQL_NUM ) ; return ( $a_rs ) ; } public function array_assoc ( $s_sql ) { $a_rs = $this -> array_make ( $s_sql , MYSQL_ASSOC ) ; return ( $a_rs ) ; } public function array_both ( $s_sql ) { $a_rs = $this -> array_make ( $s_sql , MYSQL_BOTH ) ; return ( $a_rs ) ; } } $o_mysql = new mysql_array ( 'localhost' , 'user' , 'pass' , 'db' ) ; $s_sql = "SHOW TABLES" ; $a_rs = $o_mysql -> array_assoc ( $s_sql ) ; echo '<pre>' ; print_r ( $a_rs ) ; ?>
06-Mar-2005 01:01
If you are installing PHP5 on Windows 2003 server (AKA Win 2k3) and need MySQL to work using the either the php_mysql.dll or php_mysqli.dll or both of them at the same time, and MySQl isn't showing up in phpinfo, then your php.ini is probably not loading. In the direction in the PHP 5 zip file, they will tell you to add your PHP install directory to your windows path. This should tell php where to load its php.ini from but it doesn't. If you want to get this to work, you don't have to copy any DLL's anywhere like everyone suggests. All you have to do is add the folling regsitry key to windows: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP] "IniFilePath"="C:\\PHP" simply copy the above 2 lines of code into a text file and save the file as php_ini_path.reg After you save the file it will look like a registry file. double click on it. Simply
It will make it so PHP will look for your php.ini in C:\PHP. I would assume you can edit this if you install php into a different location, but I haven't tried that. After running the reg and make sure all the up and running. Make make it work in IIS. file, make sure your php.ini is in your PHP dir appropriate things are set. This should get you sure you also follow all the steps on how to This is just an addition to the direction.
Restart apache, and everything should work. Thought that I could save someone time and frustration when upgrading, since versions 5+ do not include mySQL support by default as earlier versions apparently do.
CREATE TABLE `stats_pagecounter` ( `id` int(25) NOT NULL auto_increment, `page_name` varchar(255) NOT NULL default '', `page_hits` int(25) NOT NULL default '0', PRIMARY KEY (`id`) ) TYPE=MyISAM; ************************** COUNTING STARTS *************************/ function page_count($page) { $c_link = mysql_connect('localhost', 'username', 'password') or die('counter CONNECT error: '.mysql_errno().', '.mysql_error()); mysql_select_db('database_name'); $c_query = "SELECT * FROM stats_pagecounter WHERE (page_name = '$page')"; $c_result = mysql_query($c_query, $c_link) or die('counter SELECT error: '.mysql_errno().', '.mysql_error()); if (mysql_num_rows($c_result)) { $row=mysql_fetch_array($c_result,MYSQL_ASSOC); $pcounter = $row['page_hits']+1; $c_update = "UPDATE stats_pagecounter SET page_hits = '$pcounter' WHERE page_name = '$page'"; $c_hit = mysql_query($c_update, $c_link) or die('counter UPDATE error: '.mysql_errno().', '.mysql_error()); } else { $c_insert = "INSERT INTO stats_pagecounter VALUES ( '0', '$page', '1')"; $c_page = mysql_query($c_insert, $c_link) or die('counter INSERT error: '.mysql_errno().', '.mysql_error()); $pcounter = 1; } mysql_free_result($c_result); mysql_close($c_link); return $pcounter; } $phpself_url = $_SERVER['SERVER_NAME']. $_SERVER['PHP_SELF'].'?'. $_SERVER['QUERY_STRING']; $page_hits = page_count($phpself_url); /************************ COUNTING ENDS *************************/ /************************ Put next line in a page to show his page hits (If you want to) ************************/ echo $page_hits; ?>
70de51425df9d787 Which is the same result you get if you do "SELECT PASSWORD('hello')" directly in MySQL. Hopefully you'll never be in a situation where you have to use this, but if you need it (like I did), it's here.
noticed a behaviour which is puzzling me when using transactions. If I establish two connections within the same PHP page, start a transaction in the first connection and execute an INSERT query in the second one, and rollback the transaction in the first connection, the INSERT query in the second connection is also rolled-back. I am assuming that a MySQL transaction is not bound by the connection within which it is set up, but rather by the PHP process that sets it up. This is a very useful "mis-feature" (bug?) because it allows you to create something like this: class Transaction { var $dbh; function Transaction($host, $username, $password) { $this->dbh = mysql_connect($host, $username, $password); } function _Transaction() { mysql_disconnect($this->dbh); } function begin() { mysql_query("BEGIN", $this->dbh); } function rollback() { mysql_query("ROLLBACK", $this->dbh); } function commit() { mysql_query("COMMIT", $this->dbh); } } which you could use to wrap around transactional statements like this: $tx =& new Transaction("localhost", "username", "password"); $tx->begin(); $dbh = mysql_connect("localhost", "username", "password"); $result = mysql_query("INSERT ..."); if (!$result) { $tx->rollback(); } else { $tx->commit(); } mysql_disconnect($dbh); unset($tx); The benefit of such a Transaction class is that it is generic and can wrap around any of your MySQL statements.