PHP.mk документација

odbc_exec

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.odbc-exec.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.odbc-exec.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
odbc_exec

Референца за `function.odbc-exec.php` со подобрена типографија и навигација.

function.odbc-exec.php

odbc_exec

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_execДиректно извршување на SQL израз

= NULL

odbc_exec(Odbc\Connection $odbc, string $query): Odbc\Result|false

Директно изврши SQL изјава

Параметри

odbc

Испраќа SQL изјава до серверот за бази на податоци. odbc_connect() интерполација на низи

query

ODBC објектот за конекција, види

Вратени вредности

SQL изјавата. false при грешка.

Дневник на промени

Верзија = NULL
8.4.0 odbc очекува Odbc\Connection инстанца сега; претходно, а resource се очекуваше.
8.4.0 Враќа нов Odbc\Result инстанца сега; претходно, а resource .
8.0.0 flags Враќа ODBC резултат објект ако SQL командата беше успешно извршена, или

Види Исто така

Белешки од корисници Пример #3 Ефект на редоследот кога се совпаѓаат повеќе кодови

- Извршува подготвена изјава
21 години пред
hi all, I managed to get this little snippet working, it's pretty useful if you have long forms to be inserted into a database.

if ( ! empty ( $_POST ) ){
array_pop($_POST);
 foreach($_POST as $key => $val){
  $columns .= addslashes($key) . ", ";
    $values .= "'" . addslashes($val) . "', ";
      
 }
 $values = substr_replace($values, "", -2);
 $columns = substr_replace($columns, "", -2);
 
 $sql = "INSERT INTO table ($columns) VALUES ($values)";
 echo $sql;
 $results = odbc_exec($conn, $sql);
                 if ($results){
              echo "Query Executed";
                }else {
              echo "Query failed " .odbc_error();
            }    
}

Not the most secure in the world but, speeds up collecting data from large forms.
james @ php-for-beginners co uk
пред 22 години
I tried the following line of code

<?php
$odbc=odbc_connect("pbk", "root","") or die(odbc_errormsg());
$q="insert into pbk values(\"$name\", \"$phone\")";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

it does not work. However if I use single quotes instead of \" the thing runs smoothly

thus the following would work

<?php
$odbc=odbc_connect("pbk", "yourworstnightmare","abracadabra") or die(odbc_errormsg());
$q="insert into pbk values('$name', '$phone')";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

Also having a user dsn is no good on win2k. Always have a System DSN. I don't know yet what are the implications of the same.
rupix at rediffmail dot com
ian at eiloart dot com
If you're running NT/IIS with PHP 3.0.11 and want to use MS Access dbs with "stored procedures" you can send an ODBC SQL query like:
<?php
$conn_id = odbc_connect( "odbc_test_db", "", "", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery}" );
?>
This way you don't need to integrate query strings like 

SELECT * FROM TblObject WHERE (((TblObject.something) Like "blahblahblah"));

in the php file. You directly call the query "MyQuery" that was generated by MS Access.
gross at arkana dot de
ian at eiloart dot com
for Win32(NT) and MSAcess 2000, whenever you retrieve a date column/field, php will automatically convert it to 'yyyy/mm/dd hh:mm:ss' format regardless of the style of date you've denoted in Access.
This seems to pose a problem when you exec SELECT, UPDATE, or DELETE queries, but strangley INSERT works fine. I've tried parsing the date into the desired format, but php still yells criteria mismatch.
rmkim at uwaterloo dot ca
пред 18 години
If you are having problems with truncated text fields from ODBC queries (pe. at 4096 characters), try some of the following:

in php.ini:
- odbc.defaultlrl = 65536

in your php code, before your queries:
- ini_set ( 'odbc.defaultlrl' , '65536' );
mir eder
пред 23 години
I tried this way to see the results of a query and it works!!

$Conn = odbc_connect
("bbdd_usuaris","","",SQL_CUR_USE_ODBC );

$result=odbc_exec($Conn,"select nom from usuaris;");

while(odbc_fetch_row($result)){
         for($i=1;$i<=odbc_num_fields($result);$i++){
        echo "Result is ".odbc_result($result,$i);
    }
}
test
пред 8 години
If eval() is the answer, you're almost certainly asking the wrong question.
Анонимен
20 години пред
The following seems counterintuitive to me and so I am constantly getting burned by it.  Just thought I'd add a note for anyone else who might also get burned.

  if (!odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))

is not a good way to search for the existence of a record with Key1 = x and Key2 = y.  The odbc_exec always returns a result handle, even though there aren't any records.

Rather, you must use one of the fetch functions to find out that the record really doesn't exist.  This should work:

  if (!($Selhand = odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))
    || !odbc_result($Selhand, 1))
das_yrch at hotmail dot com
21 години пред
If a single quote exists within the field specified by your WHERE statement, ODBC fails because of a parsing error.  Although it seems intuitive, using \" around the field does not work (\"$var\").  The only solution I found was to replace all single quotes in my field with two single quotes.  ODBC interprets the first single quote as an escape character and interprets the second single quote as a literal.  Thanks to http://www.devguru.com/features/knowledge_base/A100206.html for this tip.
Sean Boulter
пред 23 години
In a previous contribution it was told that if you're running NT/IIS with PHP 3.0.11 you can use MS Access dbs "stored procedures".

That was right, but if those stores procedures have parameters you have to supply them in the command line like this:

$conn_id = odbc_connect( "odbc_test_db", "","", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery(".$param.")}" );
miguel dot erill at doymer dot com
figroc at gmail dot com
As an addition to the note about square brackets earlier:

Enclosing sql field names in '[' and ']' also allows you to use MS Access reserved words like 'date' and 'field' and 'time' in your SQL query... it seems that the square brackets simply tell Access to ignore any other meaning whatever is inside them has and take them simply as field names.
lee200082 at hotmail dot com
figroc at gmail dot com
Problem: Fieldnames in SQL-Statement have blanks and [] don't work!

Solution: Try "" instead

Ex.: 

SELECT table2.first, table1.[last name] FROM tabel1, table2 -> don't work

SELECT table2.first, table1.\"last name\" FROM tabel1, table2 -> Try this

PS: Don't forget the espace characters !!!
sk2xml at gmx dot net
yasuo_ohgaki at hotmail dot com
ODBC/MS Access Date Fields:

Matching dates in SELECT statements for MS Access requires the following format:
#Y-m-d H:i:s#

for example:

SELECT * FROM TableName WHERE Birthdate = #2001-01-07 00:00:00#

or 

SELECT * FROM TableName WHERE Birthdate BETWEEN #2000-01-07 00:00:00# AND #2001-01-07 00:00:00#

This took me forever to figure out.
akchu at at ualberta dot ca
yasuo_ohgaki at hotmail dot com
Additional links to ODBC_exec:

How to actually write the SQL commands:

http://www.roth.net/perl/odbc/faq/

http://www.netaxs.com/~joc/perl/article/SQL.html
Demystifying SQL

BIG REF MANUAL:

http://w3.one.net/~jhoffman/sqltut.htm

Introduction to Structured Query Language

Covers read, add, modify & delete of data.
petercdow на gmail точка ком
12 години пред
An SQL statement that contains quotes (i.e. ") instead of apostrophes (i.e. ') to delimit strings works fine in Access, however, in odbc_exec, it fails with 

[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.

For example:

$q = "INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES('A', 'B', 'C');"

works fine in both Access and ODBC, but

$q = 'INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES("A", "B", "C");'

fails with the above error.
rob на vendorpromotions точка com
пред 22 години
This opens select statements 'for update' by default in db2.  If you're using db2, you have to tack on 'for read only' at the end to select from SYSCAT.TABLES, for example, without firing an error like

Warning: SQL error: [IBM][CLI Driver][DB2/LINUX] SQL0151N The column "MAXFREESPACESEARCH" cannot be updated. SQLSTATE=42808 , SQL state 42808 in SQLExecDirect 

For example :

$query = odbc_exec($conn, "select * from syscat.tables for read only");
odbc_result_all($query);

will work (only for db2).  I don't know about other databases.

The select statement will work in the 'db2' command line, but not in php, because of this side effect.
delowing gmail точка com
19 години пред
It is easy to inject evil code into SQL statements. This wraps parameters in quotes so they are not executable. In your own stored procedures you can convert the string to numeric as needed.

function sql_make_string($sin){
         return "'".str_replace("'","''",$sin)."'";
}

// this may delete all data from MYTABLE
$evil = "734'; DELETE FROM MYTABLE; print 'ha ha";
$sql = "SELECT * FROM MYTABLE WHERE mykey = '$evil'";
$rst = odbc_exec($connection,$sql);

// this probably will not delete the data.
$good = sql_make_string($evil);
$sql = "SELECT * FROM MYTABLE WHERE mykey =".$good
$rst = odbc_exec($connection,$sql);
fuadMD на gmail точка ком
20 години пред
<?php
// - This is a complete working dynamic example of using: 
//    odbc_connect, odbc_exec, getting col Names,
//    odbc_fetch_row and no of rows. hope it helps
// - your driver should point to your MS access file

$conn = odbc_connect('MSAccessDriver','',''); 

$nrows=0; 

if ($conn)
{
$sql =  "select * from $month"; 
//this function will execute the sql satament
$result=odbc_exec($conn, $sql);

echo "<table  align=\"center\" border=\"1\" borderColor=\"\" cellpadding=\"0\" cellspacing=\"0\">\n";
echo "<tr> ";
// -- print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo "<th  align=\"left\" bgcolor=\"#CCCCCC\" > <font color=\"#990000\"> ";
echo odbc_field_name ($result, $j );
echo "</font> </th>";
}
$j=$j-1;
$c=0;
// end of field names
while(odbc_fetch_row($result)) // getting data
{
 $c=$c+1;
 if ( $c%2 == 0 ) 
 echo "<tr bgcolor=\"#d0d0d0\" >\n";
 else 
 echo "<tr bgcolor=\"#eeeeee\">\n";
    for($i=1;$i<=odbc_num_fields($result);$i++)
      {        
        echo "<td>";
        echo odbc_result($result,$i);
        echo "</td>";         
        if ( $i%$j == 0 )  
           {
            $nrows+=1; // counting no of rows    
          }   
      }
    echo "</tr>";
} 

echo "</td> </tr>\n";
echo "</table >\n";
// --end of table  
if ($nrows==0) echo "<br/><center> Nothing for $month yet! Try back later</center>  <br/>"; 
else echo "<br/><center> Total Records:  $nrows </center>  <br/>";
odbc_close ($conn);

}
else echo "odbc not connected <br>";
?>
phobo на на на paradise точка net точка nz
yasuo_ohgaki at hotmail dot com
If Openlink -> MS Access Database fails and gives "Driver Not Capable" error or "No tuples available" warning, use the SQL_CUR_USE_ODBC cursor when using odbc_connect()...

Siggy
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.