MySQL INSERT INTO with PHP $variable

喜夏-厌秋 提交于 2019-12-14 03:54:48

问题


I can use $variable there $strSQL = "SELECT * FROM $person"; But I can't use $variable there $sql = "INSERT INTO $person . . .

`$person` 

Don't working too...

What the difference? And how I can use $variable instead of name of the table (INSERT INTO table_name)

$sql = 'INSERT INTO $person (date, min, sec, count, temp, universal)
    VALUES("'.$date.'", "'.$min.'", "'.$sec.'", "'.$count.'", "'.$temp.'", "'.$universal.'")';
    if(!mysql_query($sql))
    {echo '<center><p><b>ERROR!</b></p></center>';}
    else
    {echo '<center><p><b>Its okay</b></p></center>';}
        }

Solve:

mysql_query("INSERT INTO $person (date, min, sec, count, temp, universal) VALUES('$date', '$min', '$sec', '$count', '$temp', '$universal')") or die(mysql_error());

回答1:


You may use like this

mysql_query("INSERT INTO `$person` VALUES(...) ")
or die(mysql_error());

You have closed the if and else wrong

just you may try this

$sql = 'INSERT INTO `name`(date, min, sec, count, temp, universal)
        VALUES("'.$date.'", "'.$min.'", "'.$sec.'", "'.$count.'", "'.$temp.'", "'.$universal.'")';

$sql = 'INSERT INTO $person (date, min, sec, count, temp, universal)
    VALUES("'.$date.'", "'.$min.'", "'.$sec.'", "'.$count.'", "'.$temp.'", "'.$universal.'")';
    if(!mysql_query($sql)) {
    echo '<center><p><b>ERROR!</b></p></center>';
    }else{ 
    echo '<center><p><b>Its okay</b></p></center>';
    }
    }// so where this comes from ?



回答2:


what is the value of your $person variable?

if it's value is a good and an existing table name into your database, no problem, you can try:

$strSQL = "SELECT * FROM {$person}";




回答3:


I like to use sprintf for this stuff.

$stmt = $pdo->prepare(sprintf("INSERT INTO %s VALUES(...)", $person));
$stmt->execute();



回答4:


Maybe with something like this :

$query = mysqli_query($connect, "INSERT INTO `$person` VALUES(...) ")
or die(mysql_error());


来源:https://stackoverflow.com/questions/28893998/mysql-insert-into-with-php-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!