如何在php中设置文件名的表名字段?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (43)

代码:

    <?php
$con = mysqli_connect("127.0.0.1","root","","dbname");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
session_start();
$id=$_GET['id'];
$sql='
SELECT Name_of_company 
  FROM companyinformation 
 WHERE id="$id"
';
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_array($result);
echo $sql;


$createfile=$rows.".txt";

$email=$_SESSION['coll'];
$rnumber=$_SESSION['roll_number'];
$rollnumber="Roll Number \n";
$Email="Email Address ";
$newline="\n";
$rollema=$Email.$rollnumber;

$myfile = fopen($createfile, "a") or die("Unable to open file!");
fwrite($myfile, $email);
fwrite($myfile," ");
fwrite($myfile, $rnumber);
fwrite($myfile, $newline);
fclose($myfile);
//echo "<script>alert('Register Successfully');window.open('studentloginpage.php','_self');</script>";
?>
提问于
用户回答回答于

mysqli_fetch_array返回一个数组(如果没有一行,则返回FALSE。)

数组中的每个条目都包含结果集中单个列的值(对于获取的一行)。

通过列的名称引用数组的元素。

$createfile = $rows['Name_of_company'].".txt";
                   ^^^^^^^^^^^^^^^^^^^

另外,考虑测试回报 :

$rows=mysqli_fetch_array($result);

if(! $rows) {
   // we got a row, continue processing
   ...
} else {
   // no row fetched
   ...
}

(也是$rows复数,它只是一个变量名称,我们可以命名它$fargedlybarp或任何其他名称,但我会倾向于用单数形式(例如($row)而不是复数形式)向未来的读者表明我们期望它包含单行。)

if( ! $row = mysqli_fetch_array($result) ) {
   // we got a row, continue processing
   ... 
} else {
   // no row fetched
   ...
}

没有插值:

$sql = 'SELECT Name_of_company FROM companyinformation WHERE id="$id"';

我们希望将$id变量的值合并到SQL文本中。如果这是一个整数值,那么我们可以这样做:

$sql = 'SELECT Name_of_company FROM companyinformation WHERE id='''
     . intval( $id ) 
     . '''' ;

否则,$id需要适当逃避的价值

$sql = 'SELECT Name_of_company FROM companyinformation WHERE id='''
     . mysqli_real_escape_string($con, $id )
     . '''' ;

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

$sql = 'SELECT Name_of_company FROM companyinformation WHERE id = ?';

扫码关注云+社区

领取腾讯云代金券