MYSQL: Insert column if not exists - php

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';
}

Related

PHP : Continue get me out

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.',';
}

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

update certain table column if else query

I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.

Get next auto increment

I know this isn't so complicated but I can't remember how to do.
I just need to know the next auto increment.
$result = mysql_query("
SHOW TABLE STATUS LIKE Media
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
...but i won't work for me, what am I doing wrong?
$result = mysql_query("
SHOW TABLE STATUS LIKE 'Media'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
The name of the table needed to be wrapped with single quotes like this: 'table_name'
So it works just fine now.
:)
The query should look like this:
SHOW TABLE STATUS WHERE `Name` = 'Media';
Another way, but slow, is:
SELECT AUTO_INCREMENT FROM information_schema.`TABLES` T where TABLE_SCHEMA = 'myScheme' and TABLE_NAME = 'Media';
The information_schema is mostly usefull for getting data from many schemes.
You can also use this function
function getNextValue(){
$query = "SHOW TABLE STATUS LIKE 'vendors'";
dbconnect();
$results=mysql_query($query);
if(mysql_errno() != 0) {
$result['count'] = -1;
$result['error'] = "Error: ".mysql_error();
} else {
$result['count'] = mysql_num_rows($results);
for($counter=0;$counter<$result['count'];$counter++) {
$result[$counter] = mysql_fetch_assoc($results);
}
}
return $result[0]['Auto_increment'];
mysql_close();
}
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name";
if you need to know the next auto_increment, then it's 99% likely you're doing it wrong. instead of the getting the next auto_increment, you should just do the insert you're about to do, then use SELECT LAST_INSERT_ID() to get the auto_increment value from that insert.
if you try to guess the next auto_increment value and you have multiple users doing it at the same time, you'll frequently get the wrong value.

MySQL check if a table exists without throwing an exception

What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
Querying the information_schema database using prepared statement looks like the most reliable and secure solution.
$sql = "SELECT 1 FROM information_schema.tables
WHERE table_schema = database() AND table_name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$tableName]);
$exists = (bool)$stmt->fetchColumn();
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Using mysqli I've created following function. Assuming you have an mysqli instance called $con.
function table_exist($con, $table){
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by #jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.
delimiter $$
CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
DECLARE _exists TINYINT(1) DEFAULT 0;
SELECT COUNT(*) INTO _exists
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = _table_name;
RETURN _exists;
END$$
SELECT TABLE_EXISTS('you_table_name') as _exists
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}

Categories