|
|
mysql_query (PHP 3, PHP 4, PHP 5) mysql_query -- Посылает запрос MySQL Описаниеresource mysql_query ( string query [, resource link_identifier] )
mysql_query() посылает запрос активной базе данных
сервера, на который ссылается переданный указатель. Если параметр
link_identifier опущен, используется последнее
открытое соединение. Если открытые соединения отсутствуют, функция
пытается соединиться с СУБД, аналогично функции mysql_connect()
без параметров. Результат запроса буфферизируется.
Замечание:
Строка запроса НЕ должна заканчиваться точкой с запятой.
Только для запросов SELECT, SHOW, EXPLAIN, DESCRIBE,
mysql_query() возвращает указатель на результат
запроса, или FALSE если запрос не был выполнен. В остальных случаях,
mysql_query() возвращает TRUE в случае успешного
запроса и FALSE в случае ошибки. Значение не равное FALSE говорит о
том, что запрос был выполнен успешно. Он не говорит о количестве
затронутых или возвращённых рядов. Вполне возможна ситуация, когда
успешный запрос не затронет ни одного ряда.
Следующий запрос составлен неправильно и
mysql_query() вернёт FALSE:
Пример 1. Пример использования mysql_query() |
<php
$result = mysql_query("SELECT * WHERE 1=1")
or die("Invalid query: " . mysql_error());
?>
|
|
Следующий запрос ошибочен, если колонки
my_col нет в таблице
my_tbl, в таком случае mysql_query()
вернёт FALSE:
Пример 2. Пример использования mysql_query() |
<?php
$result = mysql_query("SELECT my_col FROM my_tbl")
or die("Invalid query: " . mysql_error());
?>
|
|
mysql_query() также считается ошибочным и вернёт
FALSE, если у вас не хватает прав на работу с указанной в запросе
таблицей.
Работая с результатами запросов, вы можете использовать функцию
mysql_num_rows(), чтобы найти число, возвращённых
запросом SELECT, рядов, или
mysql_affected_rows(), чтобы найти число рядов,
обработанных запросами DELETE, INSERT, REPLACE, или UPDATE.
Только для запросов SELECT, SHOW, DESCRIBE, EXPLAIN, функция
mysql_query() возвращает указатель на
результат, который можно использовать в функции
mysql_fetch_array() и других функциях, работающих с
результатами запросов. Когда работа с результатом окончена, вы можете
освободить ресурсы, используемые для его хранения, с помощью функции
mysql_free_result(), хотя память в любом случае будет
очищена в конце исполнения скрипта.
См. также
mysql_num_rows(),
mysql_affected_rows(),
mysql_unbuffered_query(),
mysql_free_result(),
mysql_fetch_array(),
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_result(),
mysql_select_db() и
mysql_connect().
Duane
03-Nov-2007 05:51
Max: since you are using MySQL 5, what about creating some views to get round your problem?
Max
29-Oct-2007 12:44
Re: no support for multiple queries.
Some have suggested that multiple queries are not supported in order to avoid people being able to drop tables.
This seems a weak argument to me, since security should be handled on the server. Why not create and use a user that doesn't have the required permissions?
I find a need to use a temporary table. Without multiple queries, they're impossible. An alternative is to use a real table, which means I need to increase the permissions for the user I am using (which was previously read-only).
So, it would seem that, in my case, not supporting multiple queries has opened a security hole, not closed one.
In fact, it's plausible that one might not even have the authority to change a user's permissions, so this would mean the only alternative is to use a sub-query, which is quite a bit slower (according to my testing on mysqld5), and even crashes mysqld4.
patrick at ciphertek dot com
20-Sep-2007 10:28
If you spend a lot of time writing pages that take input from a form and insert it into a database, this function will save you time!
Please Note: You have to name your form fields the same as their corresponding table column is named in mysql for this to work.
<?php
function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) {
$fields = '';
$values = '';
foreach ($_POST as $field => $value) {
if (!preg_match("/$field, /", $exceptions)) {
$value = mysql_real_escape_string($value);
if ($sql_type == 'insert') {
$fields .= "$field, ";
$values .= "'$value', ";
}
else {
$fields .= "$field = '$value', ";
}
}
}
$fields = preg_replace('/, $/', '', $fields);
$values = preg_replace('/, $/', '', $values);
if ($sql_type == 'insert') {
$sql = "INSERT INTO $table ($fields) VALUES ($values)";
}
elseif ($sql_type == 'update') {
if (!isset($sql_condition)) {
echo 'ERROR: You must enter a sql condition!';
exit;
}
$sql = "UPDATE $table SET $fields WHERE $sql_condition";
}
else {
echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
exit;
}
if (mysql_query($sql)) {
return true;
}
else {
return false;
}
} formToDB('users', 'submit, ');
formToDB('users', 'submit, userID, ', 'update', "userID = '".$_POST['userID']."'");
?>
Jacky
16-Sep-2007 06:18
This is a replay to: a at a dot com 20-Jun-2007 04:59
I call it a bug that PHP can not execute multiple queries, if your code is vulnerable to your example, then your code is broken. The language has no business hiding your bad code! That would be like blaming items when something bad happens ..... never mind, this is common practice now a days....
Not supporting multiple queries in one execution is a problem when you want to run thousands/millions of queries over a slower network connection. I'm here because I need to execute ~ 6000000 MySQL queries to populate a random customer database. Running saved queries every few thousand statements would save a lot of time....
Not supporting this is like that magic_quotes problem which causes more problems then it solves, at least magic_quotes will finally be removed from PHP6.
[quote=a at a dot com]
###The reason that multiple queries are not supported is to help prevent exploits.###
For example, the user could enter something like:
"; DELETE * FROM users;
in the name field of a form, which would erase everything in the table when the query is executed.
By allowing mysql_query to support only single commands, this hole is closed.[/quote]
ollitech at gmail dot com
25-Aug-2007 10:53
Running an invalid delete query may not return false.
Invalid because no such record exists.
Code;
[php]
// execute it
$result=mysql_query($sql_delete_byindex);
if(!$result||$result==FALSE){
echo("<h1>Error occured while removing listing #: <i>".$rec_index."</i> </H1>");
}else if($result==TRUE){
echo("<h1>Listing #: <i>".$rec_index."</i> Deleted!</H1>");
echo "<a href=\"index.php\">Go to Start Page</a>";
}
[/php]
Query;
[code]
$sql_delete_byindex = "DELETE FROM `$mysql_table` WHERE `index` = '".$rec_index."' AND `key` = '".$key."'";
[/code]
result will be TRUE
halion at gmail dot com
09-Aug-2007 02:53
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions
this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
----------
class MySQLDB
{
private $connection; // The MySQL database connection
/* Class constructor */
function MySQLDB(){
/* Make connection to database */
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
}
/* Transactions functions */
function begin(){
$null = mysql_query("START TRANSACTION", $this->connection);
return mysql_query("BEGIN", $this->connection);
}
function commit(){
return mysql_query("COMMIT", $this->connection);
}
function rollback(){
return mysql_query("ROLLBACK", $this->connection);
}
function transaction($q_array){
$retval = 1;
$this->begin();
foreach($q_array as $qa){
$result = mysql_query($qa['query'], $this->connection);
if(mysql_affected_rows() == 0){ $retval = 0; }
}
if($retval == 0){
$this->rollback();
return false;
}else{
$this->commit();
return true;
}
}
};
/* Create database connection object */
$database = new MySQLDB;
// then from anywhere else simply put the transaction queries in an array or arrays like this:
function function(){
global $database;
$q = array (
array("query" => "UPDATE table WHERE something = 'something'"),
array("query" => "UPDATE table WHERE something_else = 'something_else'"),
array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
);
$database->transaction($q);
}
jack dot whoami at gmail dot com
01-Aug-2007 06:13
Simulating an atomic operation for application locks using mysql.
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$q = "update `table` set `LOCK`='F' where `ID`='1'";
$lock = mysql_affected_rows();
If we assume
NOT LOCKED = "" (empty string)
LOCKED = 'F'
then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.
The secret lies in the following statement taken from the mysql manual:
"If you set a column to the value it currently has, MySQL notices this and does not update it."
Of course all this is possible if the all application processes agree on the locking algorithm.
a at a dot com
20-Jun-2007 04:59
###The reason that multiple queries are not supported is to help prevent exploits.###
For example, the user could enter something like:
"; DELETE * FROM users;
in the name field of a form, which would erase everything in the table when the query is executed.
By allowing mysql_query to support only single commands, this hole is closed.
earlsinclair2001 at yahoo dot com
30-Apr-2007 01:14
On my latest project, very often, I needed to select a unique row from the database. For example: a certain user with certain username, or a row where the ID (primary key) is X. I got tired of typing these queries over and over so I created a simple function that will do just that: select one row from the database where certain field is unique. I hope this can be helpful to somebody:
<?php
function selectonerow($fieldsarray, $table, $uniquefield, $uniquevalue)
{
if(is_array($fieldsarray))
{
$fields = implode(", ", $fieldsarray);
}
else
{
$fields = $fieldsarray;
}
$result = mysql_query("SELECT $fields FROM $table WHERE $uniquefield = '$uniquevalue'") or die("Could not perform select query - " . mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows == NULL)
{
return NULL;
}
else
{
$queryresult = array();
$num_fields = mysql_num_fields($result);
$i = 0;
while ($i < $num_fields)
{
$currfield = mysql_fetch_field($result, $i);
$queryresult[$currfield->name] = mysql_result($result, 0, $currfield->name);
$i++;
}
return $queryresult;
}
}
?>
This function assumes there is a MySQL connection already established and the database to be used already selected.
Here is an example of usage:
selectonerow(fields, table name, unique field name, unique field value)
Let's say I have a users table with the fields userid, username, firstname, lastname and email. userid is the primary key and username is a unique field. If you want to select the firstname, lastname and email from the table where the userid is 4:
<?php
$fields = array("firstname", "lastname", "email");
$userdata = selectonerow($fields, "users", "userid", 4);
?>
or
<?php
$userdata = selectonerow("firstname, lastname, email", "users", "userid", 4);
?>
This will return an array to $userdata with the keys being the field name and their respective value. This is how you would print out their first name, last name and email, for example:
<?php
echo $userdata['firstname'] $userdata['lastname'] $userdata['email'];
?>
x_terminat_or_3 at yahoo dot fr
10-Mar-2007 03:27
It says in the manual:
The query string should not end with a semicolon.
However, I read somewhere that it is good practice to add a semicolon at the end of your query, and that it increases security against SQL-injection attacks. Therefore I have issued a requirement that all my developers end queries with semicolons.
So far, PHP & MySQL have happily accepted those queries, with only one exception:
If you use more then one query in the same call to mysql_query, MySQL sometimes only executes the first query and fails on the others.
JustinB at harvest dot org
08-Mar-2007 04:01
If you're looking to create a dynamic dropdown list or pull the possible values of an ENUM field for other reasons, here's a handy function:
<?php
function getEnumValues($table, $field) {
$enum_array = array();
$query = 'SHOW COLUMNS FROM `' . $table . '` LIKE "' . $field . '"';
$result = mysql_query($query);
$row = mysql_fetch_row($result);
preg_match_all('/\'(.*?)\'/', $row[1], $enum_array);
if(!empty($enum_array[1])) {
foreach($enum_array[1] as $mkey => $mval) $enum_fields[$mkey+1] = $mval;
return $enum_fields;
}
else return array(); }
?>
This function asumes an existing MySQL connection and that desired DB is already selected.
Since this function returns an array with the original enumerated index numbers, you can use these in any later UPDATEs or INSERTS in your script instead of having to deal with the string values. Also, since these are integers, you can typecast them as such using (int) when building your queries--which is much easer for SQL injection filtering than a string value.
massiv at nerdshack dot com
19-Feb-2007 06:29
Small change in mysql_dump function, to remove the ";" char at the end of the query.
<?
function parse_mysql_dump($url, $ignoreerrors = false) {
$file_content = file($url);
//print_r($file_content);
$query = "";
foreach($file_content as $sql_line) {
$tsl = trim($sql_line);
if (($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
$query .= $sql_line;
if(preg_match("/;\s*$/", $sql_line)) {
$query = str_replace(";", "", "$query");
$result = mysql_query($query);
if (!$result && !$ignoreerrors) die(mysql_error());
$query = "";
}
}
}
}
?>
... Massimo
noah at missionecommerce dot com
15-Dec-2006 06:26
I got so tired of having to type out all the 11 letters in "mysql_query()" and even more tired of having to iterate through the result set....
So I created the perfect little all purpose wrapper function, called "q()";
<?
function q($query,$assoc=1) {
$r = @mysql_query($query);
if( mysql_errno() ) {
$error = 'MYSQL ERROR #'.mysql_errno().' : <small>' . mysql_error(). '</small><br><VAR>$query</VAR>';
echo($error); return FALSE;
}
if( strtolower(substr($query,0,6)) != 'select' ) return array(mysql_affected_rows(),mysql_insert_id());
$count = @mysql_num_rows($r);
if( !$count ) return 0;
if( $count == 1 ) {
if( $assoc ) $f = mysql_fetch_assoc($r);
else $f = mysql_fetch_row($r);
mysql_free_result($r);
if( count($f) == 1 ) {
list($key) = array_keys($f);
return $f[$key];
} else {
$all = array();
$all[] = $f;
return $all;
}
} else {
$all = array();
for( $i = 0; $i < $count; $i++ ) {
if( $assoc ) $f = mysql_fetch_assoc($r);
else $f = mysql_fetch_row($r);
$all[] = $f;
}
mysql_free_result($r);
return $all;
}
}
?>
Example:
<?
$r = q('Select id,foo FROM blah');
echo $r[0]['id']; // first row, field 'id'
// for single field single row selects
// only the value is returned
$count = q('SELECT count(*) from blah');
// $count is the number
?>
Returns affected_rows and/or insert_id for anything other than select's. If you dont want field name keys then pass 0 for second parameter.
babba at nurfuerspam dot de
25-Nov-2006 03:42
Following function creates a minimal update query by comparing two arrays with old and new values (phpmyadmin-like). An easy way to use it in your forms is to print out the old values in hidden fields with name old[$key] and name the visible form fields new[$key]. Feel free to send comments via mail.
<?php
function getUpdateString($tablename, $whereclause, $old, $new) {
$changedvalues = "";
foreach($old as $key => $oldvalue) {
$newvalue = $new[$key];
if($oldvalue != $newvalue) {
if($changedvalues != "")
$changedvalues .= ", ";
$changedvalues .= "`".$key."`=";
if(!is_numeric($newvalue))
$changedvalues .= "'".$newvalue."'";
else
$changedvalues .= $newvalue;
}
}
if($changedvalues == "")
return "";
return "UPDATE ".$tablename. " SET ".$changedvalues." WHERE ".$whereclause;
}
?>
axiak at mit dot edu
23-Oct-2006 05:13
Gconner at sgi...
your function breaks when you give it a question mark!
Here's a function which correctly implements what I think you want. I'm using it in a pet project of mine.
The code:
<?php
function mysql_prepare ($query, $phs = array()) {
$phs = array_map(create_function('$ph',
'return "\'".mysql_real_escape_string($ph)."\'";'), $phs);
$curpos = 0;
$curph = count($phs)-1;
for ($i=strlen($query)-1; $i>0; $i--) {
if ($query[$i] !== '?') continue;
if ($curph < 0 || !isset($phs[$curph]))
$query = substr_replace($query, 'NULL', $i, 1);
else
$query = substr_replace($query, $phs[$curph], $i, 1);
$curph--;
}
unset($curpos, $curph, $phs);
return $query;
}
?>
veyita_angi at hotmail dot com
04-Oct-2006 09:35
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.
$buscar = mysql_query("SELECT k.*, e.Clasificacion FROM cat_plan_k k, cat_equipo e WHERE Tipo='$tipo' AND k.ID_Eq=a.ID_Eq");
while ($row=mysql_fetch_array($buscar))
{
$nombre = "e.Clasificacion";
$row[$nombre] = $Clasific; echo $row[$nombre].'convertido en '.$Clasific;
}
mysql_free_result($buscar);
cc+php at c2se dot com
02-Sep-2006 05:39
Here's a parameterised query function for MySQL similar to pg_query_params, I've been using something similar for a while now and while there is a slight drop in speed, it's far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.
<?php if( !function_exists( 'mysql_query_params' ) ) {
function mysql_query_params__callback( $at ) {
global $mysql_query_params__parameters;
return $mysql_query_params__parameters[ $at[1]-1 ];
}
function mysql_query_params( $query, $parameters=array(), $database=false ) {
global $mysql_query_params__parameters;
foreach( $parameters as $k=>$v )
$parameters[$k] = ( is_int( $v ) ? $v : ( NULL===$v ? 'NULL' : "'".mysql_real_escape_string( $v )."'" ) );
$mysql_query_params__parameters = $parameters;
if( false===$database )
return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ) );
else return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ), $database );
}
}
?>
joe
29-Aug-2006 12:45
alteration to the script reposted by
webmaster at vs2055067 dot vserver dot de
$fields = implode(array_keys($toAdd), ',');
$values = "'".implode(array_values($toAdd), "','")."'";
should really be
$fields = "`".implode(array_keys($toAdd), '`,`')."`";
$values = "'".implode(array_values($toAdd), "','")."'";
as keys like `desc` (short for description) cause errors
spencer at barekoncept dot com
23-Aug-2006 09:15
Here's an easy way to store the column names from a specified table in the array "cnames".
$result = mysql_query("SHOW COLUMNS FROM tablename");
$count = 0;
while ($row=mysql_fetch_row($result)){
$cnt = 0;
foreach ($row as $item){
if ($cnt == 0){
$cnames[$count] = $item;
$cnt++;
$count++;
}
}
}
Then, to display the results comma delimited:
foreach($cnames as $c){
echo $c.",";
}
I hope this helps some people as it took me a while to figure it out.
webmaster at vs2055067 dot vserver dot de
27-Jul-2006 08:03
in the first note the function doesn't work and the other function is pretty complicated. Here is the corrected version of the first one and a function for update.
<?php
function mysql_insert($table, $toAdd){
$fields = implode(array_keys($toAdd), ',');
$values = "'".implode(array_values($toAdd), "','")."'"; $q = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
$res = mysql_query($q)OR die(mysql_error());
return true;
}
function mysql_update($table, $update, $where){
$fields = array_keys($update);
$values = array_values($update);
$i=0;
$query="UPDATE ".$table." SET ";
while($fields[$i]){
if($i<0){$query.=", ";}
$query.=$fields[$i]." = '".$values[$i]."'";
$i++;
}
$query.=" WHERE ".$where." LIMIT 1;";
mysql_query($query) or die(mysql_error());
return true;
}
?>
rob desbois
07-Jul-2006 02:38
Note that the 'source' command used in the mysql client program is *not* a feature of the server but of the client.
This means that you cannot do
mysql_query('source myfile.sql');
You will get a syntax error. Use LOAD DATA INFILE as an alternative.
cedric ___at___ sadai ___dot___ net
05-Jun-2006 08:26
This is a quick way for adding data to a table. It is the same way than PEAR::DB, so if you are working on a server without PEAR, it enables you to keep up with your habits.
<?php
function insertIntoDB($table, $toAdd)
{
$fields = implode(array_keys($toAdd), ',');
$values = implode(array_values($toAdd), ',');
$q = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
$res = mysql_query($q)OR die(mysql_error());
return true;
}
$tToAdd = array('id'=>3, 'name'=>'Yo', 'salary' => 5000);
insertIntoDB('myTable', $tToAdd)
?>
matt
21-Mar-2006 03:45
Just realised I posted the wrong functions. Oops!
Here you go....
<?php
function compile_insert_string($data)
{
$field_names = "";
$field_values = "";
foreach ($data as $k => $v)
{
$v = preg_replace( "/'/", "\\'", $v );
$field_names .= "$k,";
$field_values .= "'$v',";
}
$field_names = preg_replace( "/,$/" , "" , $field_names );
$field_values = preg_replace( "/,$/" , "" , $field_values );
return array('FIELD_NAMES' => $field_names,
'FIELD_VALUES' => $field_values,
);
}
function insert_query($data, $table)
{
if (!is_array($data) or count($data) < 1)
{
$this->fatal_error("Insert data missing");
}
$insert = $this->compile_insert_string($data);
$query = "INSERT INTO {$table} (".$insert['FIELD_NAMES'].") VALUES (".$insert['FIELD_VALUES'].")";
return $this->query($query);
}
?>
yankee at gmeil dot com
10-Mar-2006 02:07
Another shorter possibility to print options of an ENUM as <select>-tag:
<?php
$result=mysql_query('SHOW COLUMNS FROM <your table> WHERE field=\'<you column>\'');
while ($row=mysql_fetch_row($result))
{
foreach(explode("','",substr($row[1],6,-2)) as $v)
{
print("<option>$v</option>");
}
}
?>
gconnor at sgi dot com
01-Mar-2006 05:19
I happily grabbed and used the "mysql_prepare()" function given in the first note above. All is well.
I made a slight tweak so that I could feed in NULL values without getting an empty string (or 0) instead.
// mysql_query() wrapper. takes two arguments. first
// is the query with '?' placeholders in it. second argument
// is an array containing the values to substitute in place
// of the placeholders (in order, of course).
// Pass NULL constant in array to get unquoted word NULL
function mysql_prepare ($query, $phs = array()) {
foreach ($phs as $ph) {
if ( isset($ph) ) {
$ph = "'" . mysql_real_escape_string($ph) . "'";
} else {
$ph = "NULL" ;
}
$query = substr_replace(
$query, $ph, strpos($query, '?'), 1
);
}
return mysql_query($query);
}
Sample function call:
// Check to see if all variables are defined
if ( isset($f_hostid,$f_eventid,$f_owner,$f_comment) ) {
// For numeric values, blank means NULL
if ( $f_eventid=="" ) { $f_eventid = NULL ; }
$result = mysql_prepare(
'UPDATE Hosts SET event_id=?, owner=?, comment=? WHERE id=?',
array( $f_eventid,$f_owner,$f_comment, $f_hostid )
);
if (!$result) {
$message = 'Error while updating: ' . mysql_error() . "<br />\n";
die($message);
}
echo "Update successful. <br />\n" ;
} else {
echo "Missing value. Update failed... check form logic. <br />\n" ;
}
22-Feb-2006 11:11
If, like me, you come from perl, you may not like having to use sprintf to 'simulate' placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use '?' characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it's pretty similar.
<?php
function mysql_prepare ($query, $phs = array()) {
foreach ($phs as $ph) {
$ph = "'" . mysql_real_escape_string($ph) . "'";
$query = substr_replace(
$query, $ph, strpos($query, '?'), 1
);
}
return mysql_query($query);
}
list($user, $passwd) = array('myuser', 'mypass');
$sth = mysql_prepare(
'select userid from users where userid=? and passwd=?',
array($user, sha1($passwd))
);
$row = mysql_fetch_row($sth);
if ($row !== false) {
echo "logging in as '{$row[0]}'!\n";
}
else {
echo "Invalid username and password combination.\n";
}
?>
brjann at no dot gmail dot spam dot com
22-Feb-2006 02:07
Using mysql 4 w/o stored procedures can become quite tedious, especially when writing a lot of standard sql-statements all the time.
These two functions, standardSQLInsert and standardSQLUpdate, handle most of my uncomplex cases of updating and inserting into tables. Note the use of the quote_smart function, described at http://php.net/mysql_real_escape_string, making all queries safe.
<?php
function standardSQLInsert($strTableName, $arrValuePairs){
$strSeparator = '';
$strCols = '';
$strValues = '';
foreach ($arrValuePairs as $strCol => $strValue) {
$strCols = $strCols.$strSeparator.$strCol;
$strValues = $strValues.$strSeparator.quote_smart($strValue);
$strSeparator = ',';
}
mysql_query("INSERT INTO $strTableName ($strCols) VALUES($strValues)");
}
function standardSQLUpdate($strTableName, $arrValuePairs, $arrConditionPairs){
$strSeparator = '';
$strSetStatements = '';
$strUpdateConditions = '';
foreach ($arrValuePairs as $strCol => $strValue){
$strSetStatements = $strSetStatements.$strSeparator.$strCol.'='.quote_smart($strValue);
$strSeparator = ',';
}
$strSeparator = '';
foreach ($arrConditionPairs as $strCol => $strValue){
$strUpdateConditions = $strUpdateConditions.$strSeparator.$strCol.'='.quote_smart($strValue);
$strSeparator = ' AND ';
}
$strUpdateConditions = '('.$strUpdateConditions.')';
mysql_query("UPDATE $strTableName SET $strSetStatements WHERE $strUpdateConditions");
}
$arrValuePairs = array('Col1' => 'Value1', 'Col2' => 'Value2');
$arrConditionPairs = array('Col3' => 'Value3', 'Col4' => 'Value4');
standardSQLInsert('mytable',$arrValuePairs);
standardSQLUpdate('mytable',$arrValuePairs,$arrConditionPairs);
?>
aidan at mcquay dot org
07-Feb-2006 12:03
Here's a slight revision of --celtics parse sql file function. Just fixed a typo: $sql_line != $sql
<?
function parse_mysql_dump($url, $ignoreerrors = false) {
$file_content = file($url);
//print_r($file_content);
$query = "";
foreach($file_content as $sql_line) {
$tsl = trim($sql_line);
if (($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
$query .= $sql_line;
if(preg_match("/;\s*$/", $sql_line)) {
$result = mysql_query($query);
if (!$result && !$ignoreerrors) die(mysql_error());
$query = "";
}
}
}
}
?>
Harmor
18-Dec-2005 05:32
Modification of hipsurgery submission. Here's a utility function that will return an array of a table. Don't forget to connect to the DB before calling this function.
<?php
function table_to_array($table_name)
{
$columns = array();
$result_all= mysql_query("SELECT * FROM $table_name");
$result_columns = mysql_query("SHOW COLUMNS FROM $table_name");
while ($columnRow = mysql_fetch_array($result_columns, MYSQL_ASSOC))
{
$columns[] = $columnRow
}
while ($data = mysql_fetch_assoc($result_all, MYSQL_ASSOC))
{
foreach ($columns as $column_name)
{
$array[$column_name] = $data[$column_name];
}
}
return $array;
}
?>
hipsurgery at gmail dot com
05-Nov-2005 10:30
This function will take the contents of any MySQL table, given only the table name, and return it as an index / associative multi-dimensional array in the form of:
$array[$row_number][$column_name] = $value;
I've found this very useful when you don't want to parse the table's contents in to HTML tags during a mysql_fetch_array() iteration.
<?php
function db_to_array($table_name) {
$cols = array();
$x=0;
$this_row=0;
mysql_connect(HOST,USERNAME,PASSWORD);
@mysql_select_db(DATABASE) or die( "Unable to select database");
$result_all=mysql_query("SELECT * FROM $table_name");
$result_cols = mysql_query("SHOW COLUMNS FROM $table_name");
mysql_close();
$numfields = mysql_num_fields($result_all);
for($i=0;$i<mysql_num_rows($result_cols);$i++)
{
$cols[] = mysql_result($result_cols, $i);
}
while ($data = mysql_fetch_assoc($result_all))
{
if ($x<$numfields)
{
$x++;
}
else
{
$x = 0;
$this_row++;
}
foreach ($cols as $col_name)
{
$array[$this_row][$col_name] = $data[$col_name];
}
mysql_data_seek($result_all, $this_row);
}
return $array;
}
$test_array = db_to_array("shows");
foreach ($test_array as $outer_key => $single_array)
{
foreach ($single_array as $inner_key => $value)
{
echo "\$test_array[$outer_key][$inner_key] = $value<br />";
}
}
?>
I'm just a hobbyist, so feel free to comment on my code or (worse!) tell me that there's some native PHP function that already does this!
congaz at yahoo dot dk
25-Oct-2005 02:46
Here's a little trick to help you keep track of MySQL table/column names, and the values you want to insert/select.
I always use constants instead of variables for my table/column names. The script that define the constants can then dynamically be set to initialize different table/column names if needed. However, here comes the trick.
Say you have an Insert statement like this:
<?=
// define(TABLE_DOCUMENT, 'table_name');
// define(COL_DOC_PUBLIC, 'column_name');
// etc....
$sql = "INSERT INTO ".TABLE_DOCUMENT."
(".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".$doc_public.", ".$doc_upload_tstamp.", ".$doc_name.")";
?>
Now, with long insert statements, I find it easy to loose track of which values goes with which column names. If I somehow could use the constants as variable names, keeping track of all that sql mishmash would be quite a lot easier.
As it turns out, constants names can be used as variable variables (not quite the correct definition when we're actually dealing with constants, but what the heck).
So,the sql above could instead be like this:
<?=
${COL_DOC_PUBLIC} = $doc_public;
${COL_DOC_UPLOAD_TSTAMP} = $doc_upload_tstamp;
${COL_DOC_CREATOR_NAME} = $doc_name;
$sql = "INSERT INTO ".TABLE_DOCUMENT."
(".COL_DOC_PUBLIC.", ".COL_DOC_UPLOAD_TSTAMP.", ".COL_DOC_CREATOR_NAME.") VALUES (".${COL_DOC_PUBLIC}.", ".${COL_DOC_UPLOAD_TSTAMP}.", ".${COL_DOC_CREATOR_NAME}.")";
?>
This little trick made things alot easier for me - especially when dealing with extended querys, where you might have to use the same values in severel insert/select statements. Another thing is, that you can wait to use addslashes()/my_sql_real_escape_string until you create the "variable constants" - thus the task of remebering which values have been prepared to be used in an sql-statement has become fool-proof.
Hope somebody finds this usefull...
php at arcannon dot com
01-Oct-2005 03:30
I believe there is a typo in celtic at raven-blue dot com version with:
if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
I think you really ment:
if (($tsl != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
I changed the $sql to $tsl
celtic at raven-blue dot com
10-Sep-2005 07:03
Here's a revision of ix at nivelzero -and- thomas at pixur's code. This SQL dump parser fixes the check for comments that was present in the old (ie. a '--' located anywhere in the string would make it ignore that line!), and adds the check for the # comment. That had me thinking.
<?php
function parse_mysql_dump($url, $ignoreerrors = false) {
$file_content = file($url);
$query = "";
foreach($file_content as $sql_line) {
$tsl = trim($sql_line);
if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {
$query .= $sql_line;
if(preg_match("/;\s*$/", $sql_line)) {
$result = mysql_query($query);
if (!$result && !$ignoreerrors) die(mysql_error());
$query = "";
}
}
}
}
?>
thomas -at - pixtur -dot- de
15-Aug-2005 02:14
a comment on nivelzero's excellent sql-dump-script.
It was excactly what I was looking for. Sadly in my case the sql-dump had dos-style linebreaks. Changing the regex to ...
if(preg_match("/;\s*$/", $sql_line)){
... will make the function working on both platforms. Thanks for the script.
ix at nivelzero dot ro
14-Aug-2005 03:07
here's a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say "here's a short and simple script" and it has a 100 lines?). the script skips comments and allows ; to be present within the querys
<?php
function parse_mysql_dump($url){
$file_content = file($url);
$query = "";
foreach($file_content as $sql_line){
if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
$query .= $sql_line;
if(preg_match("/;[\040]*\$/", $sql_line)){
$result = mysql_query($query)or die(mysql_error());
$query = "";
}
}
}
}
?>
kagekonjou at gmail dot com
31-May-2005 10:06
Due to the easy ways SQL can be injected into websites and thus virtually ruin a website that is dependant on databasing, I created a 'prepare' function similar to the way sprintf works.
<?php
function prepare() {
$data = func_get_args();
$query = $data[0];
$tokens = split("[\&\?\~]", $query);
$preparedquery = $tokens[0];
$count = strlen($tokens[0]);
for ($i=1; $i<count($tokens); $i++) {
$char = substr($query, $count, 1);
$count += (strlen($tokens[$i])+1);
if ($char == "&") {
$fp = @fopen($data[$i], 'r');
$pdata = "";
if ($fp) {
while (($buf = fread($fp, 4096)) != false) {
$pdata .= $buf;
}
fclose($fp);
}
} else {
$pdata = &$data[$i];
}
$preparedquery .= ($char != "~" ? mysql_escape_string($pdata) : $pdata);
$preparedquery .= $tokens[$i];
}
return $preparedquery;
}
?>
This function has been stress-tested, and does work. Example use:
$prep_query = prepare("SELECT ?,? FROM ? WHERE '?' LIKE '&'", "lastname", "address", "addressbook", "lastname", "B%");
$prep_query now has the value of "SELECT lastname,address FROM addressbook WHERE 'lastname' LIKE 'B%'"
In essence, as explained in the Wildcard Rules, ? is a quoted string, & is quoted from file, and ~ is raw ('AS-IS'). This function is to be used to make-safe SQL that is touched by a web interface. A main example would be forum pages (Ie. thread.php?fid=12&tid=12345). SQL could be injected at this point, such as " thread.php?fid=12&tid=12345'; DELETE FROM prefix_posts WHERE `id` LIKE '1%' ", which would essentially destroy that forum unless routine backups are made. This function, if used properly, can prevent any type of injections, turning the above injection into " thread.php?fid=12&tid=12345\'; DELETE FROM prefix_posts WHERE \`id\` LIKE \'1%\' ", making it look for thread-id of everything from 12345 to 1%', making it a safe, though broken SQL.
Comments and suggestions are welcome, and use of this function is free and under the Honor System (hoping you give credit where credit is due), since I'm too lazy to tack on a GNU.
wjyong at sh163 dot net
30-Apr-2005 04:21
The following query is not valid as expected:
<?php
$username = 'dicteworld';
$username{4} = '';
$sql = "SELECT * FROM `user` WHERE `User` = '$username'";
print($sql); $res = mysql_query($query);
$row = mysql_fetch_array($res);
print_r($row);?>
Pay more attention that null string '' is equivalent to '\0',therefore SQL statement above is equivalent to SELECT * FROM `user` WHERE `User` = 'dict\0world',though printing string is right.
jon at websandbox dot net
25-Jan-2005 05:25
I think it's important to note (for newbies, like me especially) that an empty result is not the same as an error:
<?php
$rs = mysql_query("SELECT `foo` FROM `bar`")
if($rs) {
echo mysql_num_rows($rs); }
andregodin at gmail dot com
18-Nov-2004 01:03
Another "dumping" function but with the optional possibility to choose wich field_name to be dumped. "Have Fun and please email me if you do optimization of this code"
<?php
function mysql_format($strTemp){
$bad_chars= array("\\", "'", "\"");
$good_chars = array("\\\\", "''", "\"\"");
return str_replace($bad_chars, $good_chars, $strTemp);
}
function mysql_dump_table(){
|
|