9

I am currently learning PHP, and I'm working on a Registration Form. Somewhere in my code I have these statements

$query = "SELECT `stud_no` FROM `tb_registered_users` WHERE `stud_no`='$studno'";

and

$query = "INSERT INTO `tb_registered_users`
VALUES ('".$studno."','".$firstname."','".$lastname."')";

but instead I want to declare this variable and use it in the queries mentioned above

$mysql_tb = 'tb_registered_users';

So what is the correct syntax for this?

ransan32
  • 225
  • 2
  • 3
  • 9

7 Answers7

11
$query = "INSERT INTO `" . $mysql_tb . "`
VALUES ('".$studno."','".$firstname."','".$lastname."')";
nickb
  • 59,313
  • 13
  • 108
  • 143
10
<?php
$mysql_tb = 'tb_registered_users';
$query = "SELECT `stud_no` FROM `{$mysql_tb}` WHERE `stud_no`='$studno'";
$query = "INSERT INTO `{$mysql_tb}` VALUES ('".$studno."','".$firstname."','".$lastname."')";
Yueyu
  • 171
  • 1
  • 6
1
$mysql_tb = 'tb_registered_users';

$query = "SELECT `stud_no` FROM `".$mysql_tb."` WHERE `stud_no`='$studno'";
Elijan
  • 1,406
  • 1
  • 8
  • 11
1

You can just do it as

$query = "SELECT `stud_no` FROM " . $mysql_tb . " WHERE `stud_no`='$studno'";

but I would recommend looking into PDO ( http://www.php.net/manual/en/book.pdo.php && http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/).

qooplmao
  • 17,622
  • 2
  • 44
  • 69
1
$query = "SELECT `stud_no` FROM `".$mysql_tb."` WHERE `stud_no`='$studno'";

and

$query = "INSERT INTO `".$mysql_tb."` VALUES ('".$studno."','".$firstname."','".$lastname."')";

You may also want to look into using something like PDO which will allow you to use named parameters and avoid SQL injections.

Jenga
  • 76
  • 2
1

Also worked for me if using double quotes:

$newDataInput = "INSERT INTO $mysql_tb (Date,Time) VALUES ('$date','$time')";
1

BTW you can also use sprintf function to do the same thing as show below

(PHP 4, PHP 5, PHP 7) sprintf — Return a formatted string

$mysql_tb = 'tb_registered_users';
$query1 = sprintf("SELECT `stud_no` FROM `%s` WHERE `stud_no`='$studno'",$mysql_tb);
$query2 = sprintf("INSERT INTO `%s` VALUES ('".$studno."','".$firstname."','".$lastname."')",$mysql_tb);

Just put %s in place where you want to replace the value and then use second parameter as variable as shown in here. It works as same as function in c language and c++. You can replace multiple values also with multiple parameters. Here is php manual help

https://www.php.net/manual/en/function.sprintf.php Hope that helps

mohitesachin217
  • 451
  • 5
  • 14