Why my second if is never executed ? It seems like the continue sentence get me out of the foreach. I have tried the elseif without success.
foreach($columns as $i=>$column)
{
// Check if column exists
$sql = "SELECT '$column' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database' AND TABLE_NAME = '$strTable'";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
continue;
}
$sql = "alter table '$strTable' add column '$column' varchar (30)";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
}
$cols .= $column.',';
}
You're not testing whether the query found any rows. mysqli_real_query() is successful as long as it didn't get an error, but that doesn't mean the query matched anything. You need to get the result of the query.
Also, you're just checking whether the table exists, not whether that column exists in the table.
continue skips the entire rest of the loop body. You should use else to execute the second block when the column isn't found.
Use mysqli_query() if you want to use the result. Otherwise, you need to call mysqli_use_result() and mysqli_store_result() first; see difference between mysqli_query and mysqli_real_query
foreach($columns as $column)
{
// Check if column exists
$sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '$database' AND TABLE_NAME = '$strTable' AND COLUMN_NAME = '$column'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0)
{
echo 'Column '.$column.' already exists! <br>';
} else {
$sql = "alter table '$strTable' add column '$column' varchar (30)";
if(mysqli_real_query($link, $sql))
{
echo 'Column '.$column.' was created! <br>';
}
}
$cols .= $column.',';
}
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 have a simple mysqli code to select the current AUTO_INCREMENT value in a table named bookings.
After the code executes, nothing happens.I do not get any output in the screen.
Here is the code.
if ($result = mysqli_query($conn, "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = titan3d AND TABLE_NAME = bookings", MYSQLI_USE_RESULT)) {
if (!mysqli_query($conn, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($conn));
}
myslqi_stmt_fetch_assoc($result);
var_dump($result);
}
Is there something wrong with this code.Can somebody sort it out?
You have a syntax error in the query, you didn't quote the strings. And then you need to fetch the result row.
if ($result = mysqli_query($conn, "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'titan3d' AND TABLE_NAME = 'bookings'", MYSQLI_USE_RESULT)) {
$row = mysqli_fetch_assoc($result);
echo "Auto-increment is {$row['AUTO_INCREMENT']}";
} else {
echo mysqli_error($conn);
}
I have a mysql 'udate' query with 'where' condition checks '$mobile' with table
column_field 'Mobile', if the value from 'textfield' to the 'where'
condition is not matching with table column_field (Then the updation will
not occur on table row).
If the 'where' condition does NOT match on the table column_field
'Mobile'='$mobile' , how can i print "Error Message" on php code.
<?php
$sql ="update mytable set total_amount = total_amount + '$total_amt',
remaning_points = earned_points - redeemed_points where Mobile = '$mobile'";
$result = query($sql);
if (!$result)
{
echo "USER NOT EXISTING";
exit;
}
else
{
echo "UPDATED";
}
?>
You can easily do it as per answers or comments here, but the ideal way to do such things is to check for existence of the record, before you perform insert/update anything in database.
$query = 'select * from table where mobile="' . $mobile . '"';
$result = mysqli_query($con,$query);
if ($result->num_rows > 0) {
$query = 'update mytable set total_amount = total_amount + ' . $total_amt . ',
remaning_points = earned_points - redeemed_points where Mobile = "' . $mobile . '"';
$result = mysqli_query($con,$query);
}
else {
echo "No record matched";
}
You can send this message to the other page by using Session or GET. This will your code will ensure ACID properties of Database. It should perform the check before performing Data Manipulation Language (DML) Statements.
Have you seen the mysql function mysql_affected_rows()?
It returns how many rows/entrys were affected by your update query. If this functions returns zero (0) then it "failed" (the user does not exist).
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 am trying to add a column by checking if it exists. If not it should give message that it already exists with the code below.
$prefix = 'vm_';
$col_name = 'checking';
$col = "SELECT ".$col_name." FROM ".$prefix."users";
if (!$col){
$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query($insert_col);
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
But it doesn't add any column and directly displays message that the column already exists.
You never execute your query, your condition is instead your query string:
if (!$col) { //always false, since a nonempty string is always truthy
Here is the final code. There was stupid mistake; I didn't use mysql_query for $col
$prefix = 'vm_';
$col_name = 'checking';
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
if (!$col){
//$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query("ALTER TABLE ".$prefix."users ADD ".$col_name." DATETIME NOT NULL");
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
You have to run your query before you check statements with it. It's like you can't see whether the box is empty of not (i.e. result of your query) without opening the box (i.e. running the query)
Replace your line 04 with this
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
Then your problem will be solved
For more information on mysqli, please read this article
You might consider moving on to PDO statements as well.
Hope this helps
You haven't executed your query. First execute your query, then check the condition on it.
This is what I did and it works:
$db= new mysqli('host','user','password','db');
$query = "SHOW COLUMNS FROM tablename LIKE 'columnname'";
$db->query($query);
if(empty(empty($db->num_rows)) {
$alter = "ALTER TABLE tablename ADD columnname varchar(50) NOT NULL";
$db->query($alter);
} else {
echo 'column exists';
}