<?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.
Related
What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.
I just create a Remote MySQL access from my other database server (remote) and I can see tables in it :
// SHOW ALL TABLES NAME
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]} <br>" ;
}
I can also see what columns name on each tables by using this :
// SHOW COLUMNS NAME OF A TABLE
$sql = 'DESCRIBE wp_ps_product_sku';
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
echo "Column: {$row[0]} <br>" ;
}
but why I can't see any rows inside each table?
$sql = 'SELECT * wp_ps_product_sku';
$result = $conn->query($sql);
print_r($result);
it always gives me an empty result. for any tables. same result. it's always empty. what did I missed here? is it possible that server just give me an access to read the database structure only, but not the data?
thank you.
On your select statement, you are missing the 'from' clause.
select * from wp_ps_product_sku;
I keep getting this error Error: Unknown column 'joinedactivities.searchact id = searchact.id' in 'on clause'. I have checked table names and tried changing it but I keep getting errors.
I have tables:
joinedactivities- id, user id(foreign key), searchact id(foreign key)
searchact-id,postcode, lat, long, hobby, venue
I am trying to display rows from table searchact from the foreign key searchact id.
$user=$_SESSION['id'];
$sql ="SELECT * FROM `joinedactivities` JOIN `searchact` ON `joinedactivities.searchact id = searchact.id` WHERE `user id`=$user ";
$result = mysqli_query($conn, $sql)or die("Error: ".mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// output data of each row
echo "Hobby : " . $row["searchact id"];
}
} else {
echo "You have not joined any groups";
}
Backticks enclose database objects. So you're telling the query engine that this entire thing is a single object (in this case a column):
`joinedactivities.searchact id = searchact.id`
I don't think you have a column named joinedactivities.searchact id = searchact.id, so the query is failing. (And even if you did have a column named that, it would still be an incomplete ON clause.) Enclose individual database objects in backticks:
`joinedactivities`.`searchact id` = `searchact`.`id`
Your backticks are incorrect:
`joinedactivities.searchact id = searchact.id`
^--------------------------------------------^
You've turned that entire string into a single identifier. You probably want something more like
`joinedactivities`.`searchact_id` = `searchact`.`id`
And note that NONE of those identifiers are reserved words, which means that the backticks are not necessary at all.
Your code is right but a slight mistake - Wrong backtracks. Use the code below
$user=$_SESSION['id'];
$sql ="SELECT * FROM `joinedactivities` JOIN `searchact` ON `joinedactivities`.`searchact id` = `searchact`.`id` WHERE `user id`=$user ";
$result = mysqli_query($conn, $sql)or die("Error: ".mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// output data of each row
echo "Hobby : " . $row["searchact id"];
}
} else {
echo "You have not joined any groups";
}
Hope this helps you
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'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}