I am creating form in Wpforms. I am adding code to make dropdown menu populated with data from database.
I have code next:
function wpforms_sql_list(){
$hostname = "localhost";
$username = "username";
$password = "password";
$dbName = "DB name";
$connect = mysqli_connect($hostname, $username, $password, $dbName);
$query = "SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'DB name'";
$result = mysqli_query($connect, $query);
$sqlitem = array();
while($row1 = mysqli_fetch_array($result)){
array_push( $sqlitem, $row1);
}
foreach($sqlitem as $raw1){
return apply_filters( 'wpforms_sql_list', $raw1);
}
}
Now I have problems because if I run in wordpress I get only dubled first database table in dropdown menu.
If I make:
return apply_filters( 'wpforms_sql_list', $sqlitem);
I get correct number of table but instead of names is written array.
Picture of result
Can anybody help me?
Thank you in advance.
Please Follow the wordpress structure to retrieve data from wordpress database like below way :
1) wordpress table see(https://prnt.sc/q71e1q)
2) Fetch data from wordpress table
global $wpdb;
$data = $wpdb->get_results("SELECT * FROM `table_name`");
echo "<select>";
foreach($data as $damenu){
echo "<option>".$damenu->name."</option>";
}
echo "</select>";
3) Output :
Related
Soo, I need to make a side category system but I am litlle bit confused about it. Can someone help me out ?
Here is my PHP
<?php
// Conncetion to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shop";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL Query
$sql = "SELECT category_id, category_name, category_link, parent_id, sort_order FROM category2 ORDER BY parent_id, sort_order, category_name";
$result = mysqli_query($conn, $sql);
//Create a multidimensional array to hold a list of category and parent category
$category = array(
'categories' => array(),
'parent_cats' => array()
);
//Build the array lists with data from the category table
while ($row = mysqli_fetch_assoc($result)) {
//creates entry into categories array with current category id ie. $categories['categories'][1]
$category['categories'][$row['category_id']] = $row;
//creates entry into parent_cats array. parent_cats array contains a list of all categories with children
$category['parent_cats'][$row['parent_id']][] = $row['category_id'];
}
function buildCategory($parent, $category) {
//Code HERE...
}
echo buildCategory(0, $category);
Soo, when you are on homepage then I just need every parent elements with "category_id = 0", then if someone click any parent category should shows up his children, but these childrens has another childrens and etc. etc. but it needs to show always parent elements with "category_id = 0".
I found live example here: https://papiernictvotriomat.sk
Also posting here image of my database:
You can change your database a little and add a field with all the way up to the root category separated by comma, but this is not a "good option" in the relational world.
The simples way is just get all categories you have - like you're doing - and create the hierarchy with a recursive function:
<?php
$conn = mysqli_connect('localhost', 'root', 'l2mago666', 'stack');
# This ensure the root one come first
$res = mysqli_query($conn, 'SELECT * FROM categories ORDER BY parent');
$categories = [];
while($rs = mysqli_fetch_assoc($res)) {
if (!$rs['parent'])
$categories[$rs['id']] = $rs;
else
$rows[] = $rs;
}
function lookup(&$set, $r) {
foreach($set as &$s) {
if ($s['id'] == $r['parent']) {
if(!isset($s['childs']))
$s['childs'] = [];
$s['childs'][$r['id']] = $r;
} else {
if(isset($s['childs']))
lookup($s['childs'], $r);
}
}
}
foreach($rows as $r)
lookup($categories, $r);
print_r($categories);
This should help you create the HTML, of course, with another recursive function.
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
This is my database of mysql on the web
This is my database on the web
This is the PHP file to access the database to get a JSON file, first I select all the "category" cell in the table, then loop through the category, and then loop through the other columns of a category, and assign to an array of $data2, after that assign $data2 and category to br an array of $data, which is the json I want to display.
<?php
header("Access-Control-Allow-Origin: *");
$user = "u348833238_rest"; /* User */
$password = "a!23286029"; /* Password */
$dbname = "u348833238_rest"; /* Database name */
$host = "localhost";
$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// $sel = mysqli_query($con,"select * from restaurant");
// $data = array();
// while ($row = mysqli_fetch_array($sel)) {
// $data[] = array("dishes" => ["name"=>$row['food'], "price"=>$row['price']] , "category"=>$row['category']);
// }
// echo json_encode($data);
$sel = mysqli_query($con,"select distinct category from restaurant");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$c = $row['category'];
$sel2 = mysqli_query($con,"select * from restaurant where category = $c ");
$data2 = array();
while ($row2 = mysqli_fetch_array($sel2)){
$data2[] = array("name"=>$row2['food'], "price"=>$row2['price']);
}
// echo $data2;
$data[] = array("category"=>$row['category'], "dishes"=>$data2);
}
// echo $data;
echo json_encode($data);
?>
How the JSON is not displayed properly as the array of property "dishes" is empty as below:
the array is empty
I’d recommend turning errors on so you can see where the problem is.
At a guess it’s here:
select * from restaurant where category = $c
Should be:
select * from restaurant where category = '$c'
I have created a series of web pages one creates users into a sql database another page looks up all of these users then needs to show them in a drop down list for another database input.
On calling the php file and using echo to print out the array it works fine however when i put it within my html file the drop down menu simply displays "$username_array[] = "\"".$row['Username'].""\" once I believe its something to do with escaping quotes however cant figure it out any help would be greatly appreciated!!
This is the code held within the html file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
echo "<label class=\"input\" for=\"investigator\" type=\"input\">Investigator:<select id=\"investigator\" name=\"investigator\">";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
$username_array = array();
$sql = mysql_query("SELECT `Username` FROM `user`");
while ($row = mysql_fetch_array($sql)){
//echo $username_array[] = "\"".$row['Username']."\"";
echo "<option value='null'>"$username_array[] = "\"".$row['Username'].""\"</option>";
}
echo "</label>";
mysql_close($conn)
?>
I want the username array to display one user after the other within a drop down list however currently just echos out the option value line without any interpretation
UPDATE
I've now changed the code to this
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<select id="investigator" name="investigator">';
$resource = mysql_query("SELECT `Username` FROM `user`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row['Username'].'">'.$row['Username'].'</option>';
}
}
echo '</select>';
mysql_close($conn)
?>
however the html outputs the script rather than a drop down list and the usernames
html output
'; $resource = mysql_query("SELECT Username FROM user"); if($resource && mysql_num_rows($resource)) { while ($row = mysql_fetch_assoc($resource)){ echo ''; } } echo ''; mysql_close($conn) ?>
any help would be appeciated I just really need to get this working as its been bugging me for days!
This will do what you need
echo '<select id="investigator" name="investigator">';
$resource = mysql_query("SELECT `Username` FROM `user`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row['Username'].'">'.$row['Username'].'</option>';
}
}
echo '</select>';
BUT you should also move to mysqli or PDO as mysql_* is depreciated
I have changed $sql to $resource as it is not an SQL statement but a resource.
I'd change your code to something similar to this:
echo "<select>";
while ($row = mysql_fetch_array($sql)) {
echo "<option value=\"VALUE\">".$row['Username']."</option>";
}
echo "</select>";
I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);