Using PHP variable as name of table in MySQL - php

use php variable in name of mysql create table
I want to use a PHP variable ( $userAltId ) as the name of the SQL table I am creating. However, despite looking at several examples, I have been unable to successfully create a table with this PHP variable. Using echo I have shown that the variable ( $userAltId ) does contain the predicted value, and if I plug in that value instead of the variable I can successfully create the table.
My latest attempt at the code is below, notice I use $useAltId three times, from creating, inserting, and selecting. Thanks for the help!
<?php
$con=mysqli_connect('localhost', 'alexpnqo_johnny', '?KlI+TtfNEIO', 'alexpnqo_johnny');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$userAltId = $_SESSION['userAltId'];//I am passing $userAltId from another php file
// escape variables for security
$FBname = mysqli_real_escape_string($con, $_POST['FBname']);
echo $userAltId;//echos desired value
$sqlFriendList="INSERT INTO '$userAltId' (FacebookFriend)
VALUES ('$FBname')";
if (mysqli_query($con,$sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);";
}
echo "You have added ";
echo $FBname;
echo " to your friend's list!";
echo "<br>";
echo "Below is your friends list";
echo "<br>";
echo "<br>";
$result = mysqli_query($con, "SELECT FacebookFriend FROM '$userAltId'");
echo "<table border='1'>
<tr>
<th>Friends List</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FacebookFriend'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Use backticks $userAltId to all your queries (table name) so that it'll read your variable even spaces.
$sqlFriendList="INSERT INTO `$userAltId` (FacebookFriend) VALUES ('$FBname')";

Related

Why is data is not printed on webpage, after being fetched from mysql database?

$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
echo "Your food complain has been successfully fetched";
echo "<table border='1'>
<tr>
<th>Username</th>
<th>PNR Number</th>
<th>Food Complain Status</th>
</tr>";
while($row = mysqli_fetch_array($retval))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['pnrno'] . "</td>";
echo "<td>" . $row['complain_status'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "\r\n";
} else {
echo "Error: " . $retval . "<br>" . mysqli_error($conn);
}
Code inside the while loop is not getting executed(I think so), "Your food complain has been successfully fetched" this message is getting printed, table is formed, but username, pnrno, and complain_status after being fetched from database is not printed on webpage. Why is it so, please help.
Assuming the data exists, and you're sending the query the correct parameter, the likely culprit is how you're using your row variable. Since you're not telling mysqli to fetch the array in an associative manner, it's defaulting to an index.
You need to change your fetch function to:
mysqli_fetch_array($retval, MYSQLI_ASSOC)
$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
Your if is going to execute if the query successfully executes.
However, a query for a non-existent row will succeed, with zero rows.
You'll want to check the number of rows returned by the query, and show an error if there aren't any matching ones.

php/sql : don't echo show data correctly

i have a problem with my php and sql code. I trying to make code that when i enter some data that related with the database, the output should show 'zero' if the row user_designid equal to 0 and if vice versa it will show 'one'.
but the problem is both of output only show the first anwser ('zero').
Php file (co.php is my config)
<?php
require "co.php";
$link = mysqli_connect($h,$u,$p,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$q = "select * from tab_ss_user where User_name ='".$_POST['name']."'";
$result = mysqli_query($link,$q);
if($result){
echo "<table border='1' >
<tr>
<td align=center> <b>user Id No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Password</b></td>
<td align=center><b>responsibility</b></td></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center><option>$data[0]</option></td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
//this is the problem
if($data['User_DesignID'] == 0 ){
echo "<td align=center> zero </td>";
}
else{
echo "<td align=center> one </td>";
}
echo "</tr>";
}
echo "</table>";
}
else{
echo ' Failed';
}
?>
that all thank you.
You are not referencing the field correctly See enter link description here
When using mysqli_fetch_row, the result is an associative array so $data['User_DesignID'] will not be referenced correctly.
please make sure your column name is "User_DesignID"
if($data['User_DesignID'] == 0 ){
(Posted on behalf of the OP).
Thanks to Jeffrey idea, I have found an answer (please refer to Jeffrey's answer on this page).
And also if you want to use column name instead please use mysqli_fetch_assoc instead of row.

one PHP function to handle different MySQLi select statements

I have two MySQL tables with number of columns. The table structure is given below,
1.pictures
postedON
caption
imageName
thumbName
imageLocation
thumbLocation
2.Videos
postedOn
category
Link
I am using the folowing PHP function to fetch data from DB using a select command.
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
//print_r($result);
//echo "Affected rows: " . mysqli_affected_rows($this->db_connection);
//var_dump($result);
echo "<table>";
echo "<tr>";
echo "<th>Date Posted</th>";
echo "<th>Category</th>";
echo "<th>Link</th>";
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>" . $row['postedOn'] . "</td>";
echo "<td>".$row['category']. "</td>";
echo "<td>" . $row['link'] . "</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
}
The problem with this function as you can see, it can only serve only one table and not dynamic. Can someone please explain the way to dynamically fetch data from different table with different number of columns using only one PHP function? Thanks
Try using mysqli_fetch_fields()
<?php
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
$fieldinfo = mysqli_fetch_fields($result);
echo "<table>";
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<th>".$val->name."</th>";
}
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<td>" . $row[$val->orgname] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
It could be hard to explain given all the wrong premises you approach is based on, but I'll try.
First of all, you have to understand that a query like SELECT * FROM table has a very little use, next to none. Most of time you are always have some WHERE or at least LIMIT clause. So, such a function will have no use at all.
Next, you have to learn by heart that database interaction should never be intermixed with any output stuff like HTML.
Given these two premises above, your function should accept a fill qualified query as a parameter and return an array with data as a result.
For which array, in turn you can write a helper function to display its contents in the form of HTML table.
But again, such a generalized output function will be of little use as well, because, as you can see from your own example, different fields will need different formatting. So it's better to write output each time by hand.

create hyperlink from database MySQL in PHP

I want to get the registered users list on a page but not just their names, but with clickable hyperlink that will lead to their profiles. I have fetched their names but just in text form but how to add hyperlink to that text so that link should lead to their profile.
<?php
$con=mysqli_connect("localhost","root","","dva");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM apnt");
while($row = mysqli_fetch_array($result)) {
echo "<li>";echo "User Reg.";
echo $row['name'];
echo " at ";
echo $row['time'];
echo " on ";
echo $row['day'];
echo "<br>";
echo "<br>";
;
}
mysqli_close($con);
?>
I have got the data from the database and successfully printed it on the page via above code but the hyperlink still needs to be generated and I need help in that please.
Create a profile.php and use GET to get the id number of your user which you send through with the link you create where you fetch your users.

php - using a hyper link to send variable used in data base to use get command to echoe results

I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!

Categories