I have a PostgreSQL database userdb with 5 schemas.
Schema 1- Persons
Schema 2- Project
Schema 3- Shop
Schema 4- Test
I was able to connect to the database using pg_connect. How do I access a specific schema in that database?
I was able to connect to a schema when there was only one in the database. But now since I have multiple schemas I am having difficulty in accessing any specific one.
<?php
// attempt a connection
$dbh = pg_connect("host=**.****.*******.*** dbname=test user=merlin port=5433 password=passw123");
if (!$dbh) {
die("Error in connection test: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM test.country";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
echo "Country code: " . $row[0] . "<br />";
echo "Country name: " . $row[1] . "<p />";
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
Qualify the table with the schema name
select *
from my_schema.aircraft
use:
SET search_path TO myschema; or
SET search_path TO myschema, myschemab;
https://www.postgresql.org/docs/9.4/static/ddl-schemas.html
Schema-qualify the table name as Clodoaldo already advised. Or set the search_path for a permanent effect. It works much like a search path in the file system.
How permanent depends on how you set it. See:
How does the search_path influence identifier resolution and the "current schema"
Related
<?php
//after creating connection
$dbname = 'bca2y';//database name
$sql = "SHOW TABLES FROM $dbname";
$result = mysqli_query($conn , $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_row($result)) {
$table = "{$row[0]}\n";
echo "$table<br>";
if($conn == TRUE){
echo "connection is possible<br>";
}
$sqld = "DELETE FROM $table";
$resultd = $conn->query($sqld);
if($resultd === TRUE){
echo "Data deleted succesfully ";//checking if data deleted
}
else {
echo "some error<br>";// for checking if code is not running
}
}
?>
Here I am trying to find name of table and delete data from the given table
But I think there is any syntax error in using variable as a table name.
my code has not giving any error but it still not working.
If I am understanding your intention -- to find table(s) and delete them from the database, "DELETE FROM mes" does not accomplish this goal. In SQL, "DELETE FROM" removes records from the specified database. It is more common to see DELETE FROM TableName WHERE ColumnName is 'SomeValue'; -- a deletion of some set of records. But DELETE FROM TableName is a valid SQL query -- it deletes all records from the table named TableName.
If you wish to delete all records from the table names retrieved from your first query, you would need to use a variable name in your delete statement rather than the static string mes.
If you want to remove the table (not just delete the data contained therein), use DROP TABLE.
If you want to DELETE all rows in a table, you should use TRUNCATE.
DELETE will delete row per row, which might take a lot of time because a lot of stuff is done by mysql for each delete operation. TRUNCATE will empty your table almost instantly
Here's your script adapted to achieve what you want
$dbname = 'bca2y';//database name
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE '".$dbname."'";
$result = mysqli_query($conn , $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach($rows as $table)
{
$sql = "TRUNCATE TABLE `".$table['TABLE_NAME']."`";
$resultd = $conn->query($sql);
if($resultd === TRUE){
echo $table['TABLE_NAME']. " truncated succesfully ";//checking if data deleted
}
else {
echo "some error<br>";// for checking if code is not running
}
}
Your user should have TRUNCATE permissions of course. And THINK before executing this, it is a dangerous script if used on the wrong database.
I've searched a long time and didn't found correct answer for this question that i want to delete only one table from database. so i have this:
<?php
$database_name = "XXXXXX";
if (!$link = mysql_connect('XXXXXX', 'XXXXXX', 'XXXXXX')) {
die("Could not connect: " . mysql_error());
}
$sql = "SHOW TABLES FROM $database_name";
if($result = mysql_query($sql)){
while($row = mysql_fetch_row($result)){
$found_tables[]=$row[0];
}
}
else{
die("Error, could not list tables. MySQL Error: " . mysql_error());
}
foreach($found_tables as $table_name){
$sql = "DROP TABLE $database_name.$table_name";
if($result = mysql_query($sql)){
echo "Success - table $table_name deleted.";
}
else{
echo "Error deleting $table_name. MySQL Error: " . mysql_error() . "";
}
}
?>
it will list all tables from database and delete all of theme but i want to delete them one by one. something like this:
delete.php?item=ONE_OF_TABLE
drop table by querystring with table name or ...
First take a look on mysql function deprecated
Then your SQL-Syntax has to be edited by a WHERE table_name LIKE 'ONE_OF_TABLE'
or replace ONE_OF_TABLE by $_GET['item']
The code posted does exactly what you want - it drops tables one by one in a cycle. If you mean - "Show tables to end user, THAN drop them one by one" - you should print the result of SHOW TABLES query and expect some other user interaction.
I am using the following PHP document below running on my linux server:
<?
/*
** Connect to database:
*/
// Connect to the database (host, username, password)
$con = sqlsrv_connect('XXXXXX','XXXXX','XXXXXX')
or die('Could not connect to the server!');
// Select a database:
mssql_select_db('Quotes_SQL')
or die('Could not select a database.');
// Example query: (TOP 10 equal LIMIT 0,10 in MySQL)
$SQL = "SELECT TOP 10 * FROM FederalStockCards ORDER BY ID ASC";
// Execute query:
$result = mssql_query($SQL)
or die('A error occured: ' . mysql_error());
// Get result count:
$Count = mssql_num_rows($result);
print "Showing $count rows:<hr/>\n\n";
// Fetch rows:
while ($Row = mssql_fetch_assoc($result)) {
print $Row['Fieldname'] . "\n";
}
mssql_close($con);
?>
But after executing the PHP file by visiting:
http://cinicraft.com/Silverman/mssql.php
I am receiving the following output:
\n\n"; // Fetch rows: while ($Row = mssql_fetch_assoc($result)) { print $Row['Fieldname'] . "\n"; } mssql_close($con); ?>
I'm not quite sure what to make of it, is this output being returned by the MSSQL server?
You have used sqlsrv_connect while connecting. And then used all mssql functions later on. There is a difference between the two of them as mentioned here: http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx.
Use mssql_connect instead, stated at: http://php.net/manual/en/function.mssql-connect.php
Also, ensure that mssql driver is enabled
I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,
I am querying a CRM2008 database on an MS server from an apache server.
I am trying to get the contactid from a view I have created on the DB.
I return the result fine, but it's not ?encoded? the way I want it.
How can I convert the results from my query into something readable (by me and my code).
<?php
ini_set('mssql.charset', 'UTF-8');
//connect
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select
$selected = mssql_select_db($DB)
or die("Couldn't open database $myDB");
$query = " select contactid from V_UserDetails where emailaddress1 =
'me#you.com' ";
$result = mssql_query($query);
//grab it
while ($row = mssql_fetch_array($result))
{
$user_custid = ($row['contactid']);
}
echo "<b>customer ID:</b> " . $user_custid . "<br />";
outputs:
customer ID: &<DŽ���h���"
rather than the required:
customer ID: 234554345jhg54j34hg54jhg43jh5g34jhg5jhg3jhg34jg
The field is a UniqueIdentifier. In the select query I changed it to
$query = " select CONVERT(VARCHAR(36), contactid) from V_UserDetails where emailaddress1 =
'me#you.com' ";
And this pulls it from the DB as expected! Sorted!
$data=iconv("UTF-8", "ISO-8859-9", $data);
ISO-8859-9// change