检查表是否存在列,如果没有,请添加列

时间:2017-02-22 19:43:22

标签: php mysqli

我正在尝试制作简报。用户必须填写$emaila是他的电子邮件的表单。

<?php
$emaila="test@test.com";
$con=mysqli_connect("localhost","user","pass","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$val = mysqli_query("select $emaila from emails limit 1");
if($val !== FALSE)
{
mysqli_query($con,"ALTER TABLE emails ADD (".$emaila." VARCHAR(100))");
mysqli_close($con);
}
?>

它用于检查电子邮件是否已经在表格中#34;电子邮件&#34;作为列,如果它不是,它应该将他的电子邮件作为列放在表中。不知道我做错了什么......

1 个答案:

答案 0 :(得分:1)

您不使用ALTER TABLE向表中添加数据。您使用INSERT

INSERT INTO `emails` (`column_name`) VALUES '$emaila'

您的测试应该是查看表格中是否存在电子邮件:

$val = mysqli_query($con,"select * from emails where email_column_name = '$emaila' ") or die (mysqli_error($con));
if($val)
{
mysqli_query($con,"INSERT INTO `emails` (`email_column_name`) VALUES '$emaila'")  or die (mysqli_error($con));
mysqli_close($con);
}

此外:Little Bobby your script is at risk for SQL Injection Attacks. 了解preparedMySQLi语句。即使escaping the string也不安全! Don't believe it?

编辑:根据注释,您需要从当前表中获取列名,循环遍历结果集,并为每个确认列名称是电子邮件地址,然后将该地址插入新表中。这是让你入门的东西:

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='database_name' 
AND `TABLE_NAME`='emails';

此查询将从电子邮件表中返回一组列名(不要忘记更改数据库名称),您可以循环使用。