I want display a table content along with column names.
I have used SQL query for columns
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable"
and I have used SQL query for content
"SELECT * FROM $mytable"
Both are working fine. Only thing is that, order of columns is different. Some times its just reverse. sometimes it is reverse with some shift of 2-3 columns depending on number of column in $mytable.
You need to include an order by when you query ALL_TAB_COLUMNS on COLUMN_ID:
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable ORDER BY COLUMN_ID".
This orders the columns by the order created.
Probably a better approach is to simply read the column names from the returned resultset. This means you need only one query:
$conn = oci_connect($username, $password, $connectionString);
$stmt = oci_parse($conn, 'select * from mytable');
oci_execute($stmt);
$headers = false;
while ($row = oci_fetch_assoc($stmt)) {
if (!$headers) {
// this will only output the headers on the first iteration.
print_r(array_keys($row));
$headers = true;
}
print_r($row);
}
Or you could use oci_field_name() against the resultset but I've always felt the above method is simpler.
Edit: In case there are no results, you won't be able to get the keys (since the array is empty). You can add the following code after the while loop to handle that:
if (!$headers) {
for ($i = 1; $i <= oci_num_fields($stmt); $i++) {
echo oci_field_name($stmt, $i), PHP_EOL;
}
}
Related
From the following Queries, Which one is the most optimal and fastest to use?
[COUNT(id)]
$SQL = "SELECT name, COUNT(id) as Count FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($data['count'] > 0) {
while ($row) {
$name = $row['name'];
}
} else {
return;
}
OR [rowCount()]
$SQL = "SELECT name FROM names WHERE name = :name";
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$name = $row['name'];
}
} else {
return;
}
OR [EXISTS]
$SQLEX = "SELECT EXISTS (SELECT name FROM names WHERE name = :name LIMIT 1)";
if ($stmt->fetchColumn == 1) {
$SQL = "SELECT name FROM names WHERE name = :name";
while (row = $stmt->fetch()){
$name = $row['name'];
}
} else {
return;
}
OR [RAW]
$SQL = "SELECT name FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($row) {
while($row) {
$name = $row['name'];
}
} else {
return;
}
Also i wanted to know, Why does using $stmt->fetch() with $stmt->rowCount() allows me to fetch data, But using it with $stmt->fetchColumn doesn't?
First, if you have an index on names(name), then all should be quite comparable in speed.
Second, it is always worth trying such performance tests on your own system.
Third, if names are declared as unique (or primary key) in the names table, then all should be quite fast.
In general, though, the fastest way to determine if a row is available is:
SELECT EXISTS (SELECT name FROM names WHERE name = :name)
The LIMIT 1 in the subquery is unnecessary -- EXISTS stops at the first row (whether the database uses an index or a table scan).
In general, the first method using an aggregation is the worst solution. Without an index, it is going to result in a full table scan that reads the entire table. The second might or might not read the entire table, depending on whether the database starts returning matching rows as they are available. It also has the downside of returning more data.
Ok, it seems this question needs more than one answer...
f you need to check the existence only,
if there is an unique index for the field, all methods are equal, but some of them just make no sense.
if there is no unique index, then go for EXISTS
If you need to fetch the actual data and see if there was anything returned, then just select your data and fetch it:
if only one column from a single row is expected, then use fetchColumn()
if only one row is expected, then use fetch()
if multiple rows are expected, then use fetchAll()
and then use the resulting value to see whether your query returned any data.
So if you finally made your mind as to what you're asking about, here is the most optimal code for you:
$SQL = "SELECT name FROM names WHERE name = :name";
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (!$data) {
return;
}
foreach ($data as $name) ...
And there is nothing wrong with fetchColumn() other than your idea to use it.
I have two separate remote databases, the table in both databases is identicle and I want to copy a record from the old database to the new using PHP
While this the best way to copy new records from one database to another gives the solution as
mysqli_query($db1,"SELECT field1,field2,field3 FROM table1");
mysqli_query($db2,"INSERT INTO table1 (field1,field2,field3)");
Because of the number of fields involved I want to try and avoid naming all the fields
I was thinking of something like this...
$m = mysqli_query($db1,"SELECT * FROM table1");
****THIS IS WHERE I'M STUCK****
HOW DO I GET TO THIS FROM THE ABOVE STATEMENT?
$values = "'".implode("','",array_values($m))."'";
$columns = implode(",",array_keys($m));
So I can do this
mysqli_query($db2,"insert into table1 ($columns) values ($values)")
I'm aware I will need to change the PRIMARY KEY id to null.
To fetch the actual column names you could do like this:
$sql="SELECT column_name FROM information_schema.columns WHERE table_schema = 'database_name' AND table_name = table1";
Fetch the above into an array.
$result = $mysqli->query($query);
$cols = $result->fetch_array(MYSQLI_NUM);
and create comma-separated list into $columns-variable
$columns = implode(",", $cols);
For the values, just do a regular select-statement:
$sql="SELECT * FROM table1";
$result = $mysqli->query($query);
$vals = $result->fetch_array(MYSQLI_NUM);
in the end it was quite simple to modify my own code and create the array using mysqli_fetch_assoc
$m = mysqli_fetch_assoc(mysqli_query($db1,"SELECT * FROM table1"));
and then to make the id null
$m["id"] = 'replacethis';
$values = str_replace("'replacethis'","null","'".implode("','",array_values($m))."'");
$columns = implode(",",array_keys($m));
then finally...
mysqli_query($db2,"insert into table1 ($columns) values ($values)");
I get error : "Unknown column 'Array' in 'where clause'" perharps from variable $query in my code.
This is my code :
$zzz = mysql_query("SELECT alias FROM table WHERE ColumnA = 'yes'");
while($aaa = mysql_fetch_array($zzz)){
$array[] = $aaa['alias'];
}
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN ($array) ORDER BY Column1 DESC, Column2 DESC");
I want to make a SELECT query WHERE 'alias' in table2 not equal to any data in $array which come from fetch array $aaa.
I got a clue to make an array from fetch array from :
Array in SQL Query?
But, i don't know how to add 'quote' for each data in array that made from $aaa.
Could anyone tell me how to do this? :)
Why not use nested queries? Example:
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN (SELECT alias FROM table WHERE ColumnA = 'yes') ORDER BY Column1 DESC, Column2 DESC");
As noted in my below comment, however, your interaction appears to be vulnerable to injection attacks. This can be avoided to some degree, as others have stated, but as I have also stated, one of the better ways is to use PDO. Example:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM table2 WHERE alias NOT IN (SELECT alias FROM table WHERE ColumnA = :bool) ORDER BY Column1 DESC, Column2 DESC");
$stmt->bindValue(":bool","yes");
$stmt->execute();
} catch (\PDOException $e) {
// Something went wrong
}
while ($row = $stmt->fetch()) {
// do stuff with query
}
PDO ships with php 5.1.
You're trying to use $array directly, and it does not print itself the way you need to. Following the advice in the linked question, you could use implode:
$newarray = implode(", ", $array);
$query = mysql_query("SELECT * FROM table2 WHERE alias NOT IN ($newarray) ORDER BY Column1 DESC, Column2 DESC");
As for adding quotes, you can just concatenate them together. However, I'd also escape the values before quoting, to avoid SQL injection vulnerabilities:
while($aaa = mysql_fetch_array($ambilLarikAkunTerlindungi)){
$array[] = "'" . mysqli_real_escape_string($aaa['alias']) . "'";
}
I am trying to run a query to determine if a column A is true. If its true, get the contents of a different column B (possible array separated by ",") and use those contents to query a different table. My problem is, column B may be one number or may be 10 numbers all separated by "," and I need to query the second table for a column for each of the numbers of the previous query. If someone can help that would be great.
edit: I tried to use the array explode function but can't figure out how to query the next table to include those values.
I picture it being something like
query = select * from table where location = arrayValue[1] or location = arrayValue[2]
Adaptation of Telmo Marques here but improved :
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
array_walk($bcolumnArray, 'htmlentities');
//Build SQL query
$SQL = 'SELECT * FROM table';
if(count($bcolumnArray)){
$SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")';
}
//Query your second table here
$Qry = mysql_query($sql);
// Results here :
while($Res = mysql_fetch_assoc($Qry)){
print_r($Res);
}
?>
I would suggest PDO also... take a look : PDO.
Use PHP's explode() function to transform your string into an array.
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
//Build SQL query
$sql = "SELECT * FROM table WHERE ";
for($i=0; $i < count($bcolumnArray); $i++)
{
$sql .= "location = " . $value;
if($i != count($bcolumnArray)-1)
{
$sql .= " or ";
}
}
//Query your second table here
mysql_query($sql);
?>
Documentation: http://php.net/manual/en/function.explode.php
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)