PHP - drop only one table from database - php

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.

Related

delete a data from database from multiple tables

<?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.

PHP MySQL inserting multiple values from drop box selections

I have a table populated by a MySQL table, and I am trying to insert the selected rows from the table into another table.
The table look like below:
.
There are first three fields in the table are coming from two other tables depending on the Field values.
And the drop down selections are provided by user using:
$sql = "SELECT project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
$retval = mysql_query($sql) or die(mysql_error());
What will be the best way to insert these multiple selected rows into another table please? Thanks.
"select into" is the way to go.
SELECT into YourNewTable select project_proposals.id, project_proposals.title, project_proposals.description, project_proposals.academicname, flux_student_records.studentname, flux_student_records.id, flux_student_records.programme, flux_student_records.academicdiscipline FROM project_proposals JOIN flux_student_records ON project_proposals.academicdiscipline = flux_student_records.academicdiscipline
WHERE project_proposals.academicdiscipline = '$academicdiscipline' AND flux_student_records.studentname = '$studentname'";
Hope you find this usefull.
You can loop trough an post and then do some thing with that information.
So for example:
<?php
function readDataForwards($dbh) {
$sql = 'SELECT * FROM yourdb';
try {
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
#insert the data into another database
#you can also filter some duplicated items that you already
#have in the database
}
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
}
?>
this would output: the rows in the database
but it could also insert the rows into your database.

trying to count entries in a database

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,

Access a specific schema in a PostgreSQL database via PHP

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"

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Categories