I spent few days, but since I am completely new in JSON or PHP programming, can't solve my problem without your help.
Here is my problem - I have MySQL DB, I need to extract data from the table and build simple (for e.g. 2 columns) page (html or whatever) with table which consist info from my DB.
I wrote php connector, here it is:
<?php
//require_once("data_connector.php"); //!connector
$dbtype = "MySQL";
$username = ''; // USERNAME
$password = ''; // PASSWORD
$hostname = ''; // HOSTNAME
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("MASTER_TRACKER_DB",$dbhandle)
or die("Could not select MASTER_TRACKER_DB");
/*
//execute the SQL query and return records
$result = mysql_query("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "SITE_ID:".$row{'SITE_ID'}." 3G_SITE_ID:".$row{'3G_SITE_ID'}.
"<br>";
}
*/
$data = new JSONDataConnector($dbhandle, $dbtype);
//$data->render_table("MASTER_TRACKER_DB.MASTER_TRACKER","SITE_ID","SITE_ID, 3G_SITE_ID");
$data->render_sql("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER_DB.MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'", "", "SITE_ID, 3G_SITE_ID");
$data->dynamic_loading(30);
//close the connection
//mysql_close($dbhandle);
?>
From this script I see that I am able to connect to DB (I am getting Connected to MySQL message).
Also, if I comment out PHP part which build table, I see that it can build table.
So, as next step, I would like to build table using JSON, so I will use it with Webix, so I made this page:
<!DOCTYPE html>
<html>
<head>
<title>Loading from DB</title>
<link rel="stylesheet" href="codebase/webix.css" type="text/css">
<script src="codebase/webix.js" type="text/javascript"></script>
</head>
<body>
<div class='header_comment'>Loading from DB (sqllite + php)</div>
<div id="testA" style='height:600px'></div>
<hr>
<script type="text/javascript" charset="utf-8">
webix.ready(function(){
grida = webix.ui({
container:"testA",
view:"datatable",
columns:[
{ id:"SITE_ID", header:"SIZE_ID", width:200 },
{ id:"3G_SITE_ID",header:"3G_SITE_ID", width:120 }
// { id:"size", header:"Size" , width:80 },
// { id:"architecture", header:"PC", width:60 }
],
autowidth:true,
url: "data/data.php"
});
});
</script>
</body>
</html>
But seems that I missed something since it shows empty table,
Can anyone please help me to make this page working?
Thanks to all in advance,
Roman
Related
This question already has answers here:
How to secure database passwords in PHP?
(17 answers)
Closed 2 years ago.
I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database.
But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.
I added a part of my code related to this problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them
Normal practice is to put the mysql data in a separate php file. For example:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
then you can include this file in all php files which require db connection.
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>
Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>
I am trying to use php for the first time to connect to MySQL on the raspberry pi. Both the server and MySQL are running on the Pi and I want to tweak my index.html file to show some value that is in the data base. Normally for I would be able to do just that with pyton but I have no clue if I can do that with php. Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
<div class="header">
<p><strong>Welcome to Ziks</strong></p>
</div>
<p> </p>
<div class="box">
<p> Wishing every one a happy life! </p>
<form method="GET" action="ftp://47.55.90.215:21">
<input type="submit" value="Click here to view Disk">
</form>
<body>
<html>
<body>
</body>
</html>
</body>
<div class="image"></div>
<iframe src="http://free.timeanddate.com/clock/i5nb4b3g/n1127/szw160/szh160/hoc9b8578/hbw10/hfc754c29/cf100/hnc432f30/hcw2/fav0/fiv0/mqcfff/mqs4/mql25/mqw12/mqd78/mhcfff/mhs2/mhl5/mhw2/mhd78/hhcfff/hhs2/hhl50/hhw8/hmcfff/hms2/hml70/hmw8/hmr4/hscfff/hss3/hsl70/hsw3" frameborder="0" width="160" height="160"></iframe>
<video width="400" controls>
<!--<source src="///smb://zikpc/f/test.mp4" type="video/mp4">-->
<!--<source src="///smb://zikpc/f/test.ogg" type="video/ogg">-->
<source src="1.mp4" type="video/mp4">
<source src="1.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</div>
</body>
</html>
This index.html file works fine. All I want to do is write some php in it to connect to MySQL. The current method I'm using in python is:
# External module imports
import time
import os
import datetime
import MySQLdb
os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
# Connect to mysql
db=MySQLdb.connect("localhost","zikmir","gforce","temp_database")
cursor=db.cursor()
while True:
# Initialization
sensor= "/sys/bus/w1/devices/28-011620ee98ee/w1_slave"
# Open the file for sensor
file = open(sensor)
# Read all of the text in the file.
text = file.read()
# Close the file now that the text has been read.
file.close()
# Split the text with new lines (\n) and select the second line.
second_line = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temp_data = second_line.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temp = float(temp_data[2:])
# Put the decimal point in the right place and display it.
temp = temp / 1000
# Display time
t= datetime.datetime.now()
print t,temp
# Push data into mySQL
sql = "INSERT INTO time_temp VALUES(now(),%s)"
cursor.execute (sql,(temp,))
db.commit()
# Wait 5 seconds
time.sleep(5)
My question is how would I be able to do this in php within the index.html file? Any help would be appreciated!
This is my website
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
You have a number of choices. The simplest, IMHO, would be something like the following.
Rename your index.html file to index.php (make sure that your web server looks for index.php as well as index.html and index.htm).
Your index.php would then be modified to look something like this:
<?php
//Open MySQL connection
//Get the data you want into a string variable called $info
print <<< END
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
... (rest of HTML excluded for brevity)
END;
?>
Simply put the $info variable where ever you want the data to appear in the HTML data.
The construct:
print <<< END
<<<what you want to print>>>
END;
is called a "heredoc" and is very handy.
I have not described how to actually get the data from the database since your question seemed more about the process of using PHP to output HTML with data from a database. Look at the PDO documentation (PDO documentation) to quickly get up to speed on DB access in PHP.
I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.
We are Trying to Connect php & mysql we got connection successful but we are not receiving the data any ideas please guide
Also we are using mysql and php
The Connection is Successful but nogetting the data into website
enter code here`Please let me know who to correct it<html>
<head>
<title> Welcome to PDM</title>
</head>
<body>
<div>
<centre>
Good For Checking The Prices
</centre>
<?php>`
$db_host = "localhost";
$db_username = "wikiacwj_price";
$db_pass = "";
$db_name = "wikiacwj_price";
mysql_connect("$db_host","$db_username","$db_pass") or die ("Please Try Again");
mysql_select_db("wikiacwj_price") or die ("no data");
$sql = mysql_query("SELECT * FROM price_comparsion where product_name='ok'");
//write the results
while ($row = mysql_fetch_array($sql)); {
echo $row['product_name'];}
?>
</body>
</html>
The Semicolon immediately after your while statement telling the while loop to do ... nothing :)
...
while ($row = mysql_fetch_array($sql)) {
echo $row['product_name'];
}
...
shoud do the trick.