hello i am trying to do a select query from multiple tables and I made variables for the tables names and it works if I removed the variables and put the tables names instead what to do?
$table_name = $wpdb->prefix . 'student_list';
$table_name1 = $wpdb->prefix . 'courses';
$table_name2 = $wpdb->prefix . 'registration';
$registrations = $wpdb->get_results("SELECT registration_id , $table_name1.course_id ,$table_name.student_id ,$table_name1.name, $table_name1.course_name ,$table_name1.course_code FROM $table_name ,$table_name1, $table_name2 WHERE $table_name2.course_id = $table_name1.course_id and $table_name2.student_id = $table_name.student_id");
My Answer:
> If you are using PHP and MySQL, you can dynamically build your SQL query using variables for table names. Here is an example of how you can achieve this:
php
$table_name1 = "table1";
$table_name2 = "table2";
$sql = "SELECT * FROM $table_name1, $table_name2 WHERE $table_name1.id = $table_name2.id";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
// Process the data
}
} else {
echo "No results found";
}
In this example, we are using variables `$table_name1` and `$table_name2` to store the table names. Then, we are dynamically building the SQL query using these variables. Make sure to properly sanitize and validate the table names to prevent SQL injection attacks.
Rate this post
4 of 5 based on 9264 votesComments