I have selected a random table from a list/array and I want to be able to call this random table with the mysqli_query function i.e. select a table dynamically
Here is my code:
<?php
$mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Looks at all prodcuts and selects those that have special offers enabled
// Selects a random table from the array
$tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
$rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
echo "<p>".$rtable." was selected</p>";
$products = mysqli_query("SELECT * FROM '".$rtable."'");
echo "<p>".$products."</p>";
while($productRow = mysqli_fetch_array($products))
{
if ($productRow['product_specials'] == 1)
{
echo "<table>";
echo "<tr>";
echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
echo "</tr>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>" . $productRow['product_name'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>" . $productRow['product_description'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
Im at a loss of why this is not working
Thanks,
Bull
You should not quote table names with single quotes but with backticks, single quotes makes it a string instead of a table name;
Also, the function mysqli_query takes an extra parameter, the connection.
$products = mysqli_query("SELECT * FROM '".$rtable."'");
should be;
$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");
Try
$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);
Related
Iam trying to fetch the random data from mysql database, but it only fetches the same row on page refresh
I tried to run the query to get the random single row data from mysql and display on the webpage using php, but it only retrieving only the same row every time
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1
<?php
$link = mysqli_connect("host", "username", "password", "db_name");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>email_md5</th>";
echo "<th>age_group </th>";
echo "<th>age</th>";
echo "<th>income</th>";
echo "<th>Income_group </th>";
echo "<th>gender</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['email_md5'] . "</td>";
echo "<td>" . $row['age_group'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['income'] . "</td>";
echo "<td>" . $row['Income_group'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I need the random row data to be displayed everytime the page is refreshed. Will really be helpful if anyone can suggest be the best solution.
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND()
LIMIT 1";
Change the line to
$randomv=rand(min,max);
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY $randomv
LIMIT 1";
Here is my implementation in another case where I have to choose from a random id available - Yii 2 Framework
$prodcutids= \app\models\TblProduct::find()->all();
$targetproduct= ArrayHelper::map($prodcutids, 'id','id');
$productdetails= \app\models\TblProduct::findOne(['id'=>array_rand($targetproduct)]);
$productseriesname= \app\models\TblSeries::findOne(['id'=>$productdetails['Serie']]);
Or if you have an id column
$sql = "SELECT * FROM identity_explorer_demographics WHERE id=$randomv
LIMIT 1";
rand(min,max)
min specifies the lowest value that will be returned.
max specifies the highest value to be returned.
You mix it with PHP
$sql = 'SELECT * FROM `identity_explorer_demographics`';
//Perform query and parse result, E.G $sql = db::query($sql);
function getRandomRow($sql) {
$random_row = count(0, count($sql));
foreach($sql as $row => $result) {
if ($row == $random_row) {
return $row;
}
}
}
I am stuck with how to insert multiple array data of checkbox. I came across some code but I don't know how to implement them in my php code. How can I insert multiple data from checkbox in my database? Can someone help me? I really appreciate it. Thank you in advance.
html code:
<?php
include ('connect.php');
$sql2 = "SELECT * FROM owner WHERE owner_username ='".$_SESSION['username']."'";
$result2 = mysqli_query($conn,$sql2);
$row = mysqli_fetch_array($result2);
$id = $row['owner_id'];
$sql = "SELECT cat_id,name,gender,health_status,neutered,breed,color,age
FROM cat WHERE owner_fk = '$id'";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
echo "<tr>";
echo "<td>" .$row ['name']. "</td>";
echo "<td>" .$row ['gender']. "</td>";
echo "<td>" .$row ['health_status']. "</td>";
echo "<td>" .$row ['neutered']. "</td>";
echo "<td>" .$row ['breed']. "</td>";
echo "<td>" .$row ['color']. "</td>";
echo "<td>" .$row ['age']. "</td>";
echo "<td>" ."<input type='checkbox' name= 'check[]' value=''". "
</td>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn-> close();
?>
this is my php code:
<?php
include ('connect.php');
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST["check"]);$i++)
}
$p_id =$_GET ['sitter'];
$price = $_POST ['price'];
$pickup_date =$_POST ['pickup_date'];
$dropoff_date =$_POST ['dropoff_date'];
$numdays = $_POST ['numdays'];
$total =$_POST ['test'];
$sql2 = "INSERT INTO cat_sitter(sitter_fk,cat_fk, price, date_in,
date_out,total_day, total)VALUES ('$p_id','".$_POST["check"]
[$i]."','$cat_id','$price','$pickup_date','$dropoff_date','$numdays',
'$total')" or die ("Error inserting data into table");
if ($conn->query($sql2) === TRUE) {
echo "<script language='javascript'>alert('Succesfully Book.')
window.location.replace(\"book_page.php\");
</script>";
}else{
echo "error: " . $sql2 . "<br>" . $conn->error;
}
?>
Use implode function
In your case replace $_POST["check"] with implode(',',$_POST["check"]) then it will work fine fine hope so
Instead of implode and explode. You can use convert checkbox array into JSON and store in single field.
// Convert Array to JSON String
$checkArray = $_POST["check"];
$checkJSON = json_encode($checkArray);
After you fetch its value from database convert JSON into array.
// Convert JSON string to Array
//$checkJSON is variable fetched from database
$checkArray = json_decode($checkJSON, true);
print_r($checkArray); // Dump all data of the Array
I'm trying to create a dynamic header on Name which gives the user the ability to sort by ASC or DESC, the results is from the 'register'-table in MySQL. I have tried a couple of codings, but it hasn't given the correct result as of now. Hope anyone is able to help me :)
I have tried making another variable, but I couldn't manage to create the correct one.
<?php
$sql = "SELECT * FROM register";
if($sqlData = mysqli_query($db, $sql)) {
if(mysqli_num_rows($sqlData) > 0) {
echo "<table border ='1' bgcolor='#FFF' width='100%'>";
echo "<tr>";
echo "<th><a href='overview.php?order=name'>Name</a></th>";
echo "<th>Score</th>";
echo "</tr>";
while($row = mysqli_fetch_array($sqlData)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($sqlData);
} else{
echo "No results in DB";
}
} else{
echo "Error couldn't connect $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
Hm, that's not a good idea to sort table using MySQL each time user clicked on the table's header.
I suggest you to use javascript for it. Example
<?php
$con = new mysqli('localhost', 'root' ,'', 'world');
$query = 'SELECT * FROM city ORDER BY Name';
if ($result = mysqli_query($con, $query)) {
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>"
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
mysqli_close($con);
?>
This simple code will display every entries in this database. Now I would like to add a selective display option by choosing the CountryCode.
$query2 = 'SELECT DISTINCT CountryCode FROM city ORDER BY CountryCode';
How do I use the result I got from the query above and make it become radio buttons to choose what to display?
Similar to what you are doing already: Something like
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='radio' name='whatever' value='".$row['Name']."'>". $row['Name'];
}
Ofcourse the field names can be whatever you like them to be, as long as you select them in the query
Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).