How to show mysql data in html input text? - php

I have created html file with generated text, and i want to populate fields like name and date from mysql database. The thing is i am trying to show data from mysql in html input text tag. But it only shows letter S.
This is my php code:
<?php
$db_host = ''; // Server Name
$db_user = ''; // Username
$db_pass = ''; // Password
$db_name = ''; // Database Name
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
mesto,tip,obrazlozenje,vreme_slanja
FROM godisnji
WHERE id=74";
mysqli_close($con);
?>
And this is a part of my html code:
<p style="text-align:justify">1. Zaposlenom <input name="lname" type="text" value="<?php echo $result['ime_prezime'];?>"/>
na poslovima $posao, se odobrava
korišćenje godišnjeg odmora za 2018. godinu, u trajanju od 20 radnih dana.</p>

Just because...
Now this is very basic and you should learn to use PDO or at least the mysqli class. But for now...
This is a little demonstration code... ( It may have bugs as I have not run it )
<?php
// The Database Connection Stuff should be in it's own file
// and included in each file that requires a database connection.
$db_host = ''; // Server Name
$db_user = ''; // Username
$db_pass = ''; // Password
$db_name = ''; // Database Name
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create the SQL
$sql = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
mesto,tip,obrazlozenje,vreme_slanja
FROM godisnji
WHERE id=74";
// Run the SQL statement
$query = mysqli_query($con,$sql);
// Read back the ROW as an associative array
$result = mysqli_fetch_assoc($query);
// DEBUG to learn what you get back and CHECK it's what you expect!
var_dump($result);
// If it exists...
echo ($result['ime_prezime']);
mysqli_close($con);
// Then Read up on how to use PDO or mysqli Class
And as a suggestion, due to the fact you won't always have a valid value you could use instead of...
<?php echo $result['ime_prezime'];?>
Try this
<?= isset($result['ime_prezime'])?$result['ime_prezime']:'';?>
The above tests whether $result['ime_prezime'] exists, and if it does it will print it, else it will print ''.
Look up "Ternary Operators in PHP"

<?php
$db_host = ''; // Server Name
$db_user = ''; // Username
$db_pass = ''; // Password
$db_name = ''; // Database Name
// Create connection
$conn = new mysqli($db_host, $db_user , $db_pass , $db_name );
if ($conn->connect_error)
{
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
$result = "SELECT ime_prezime,datumpocetka,datumzavrsetka,broj_dana,sektor,
mesto,tip,obrazlozenje,vreme_slanja FROM godisnji WHERE id=74";
$sqlQuery = $conn->query($result);
$value = $sqlQuery->fetch_assoc()['ime_prezime'];
echo "<p style='text-align:justify'>1. Zaposlenom <input
name='lname'type='text' value='".$value."'/></p>";
$conn->close();
?>

Related

How do I query records from my database in PHP so it appears on the URL

<?php
//Create connection credentials
$db_host = 'localhost';
$db_name = '';
$db_user = '';
$db_pass = '';
//Create mysqli object
$mysqli = new mysqli ($db_host, $db_user, $db_pass, $db_name);
//Error Handler
if($mysqli->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
<?php
//Set question number
$number = (int) $_GET['n'];
/*
* Get Question
*/
$query = "SELECT * FROM `questions`
WHERE question_number = $number";
//Get result
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$question = $result->fetch_assoc();
?>
I have made a database in phpMyAdmin and am trying to query the questions I have created.
I have used this code and when I save and refresh this in the web browser it replies "No database selected12".
I have created the sql connection to the database that is all fine its just when I try to query the questions to appear on the web page it doesn't work.
the first half of the code was created in database.php file then just used in another.
Please can someone help me!!! Thanks

Store MySQLi query result in a PHP variable

All i want to do is to store the name of the guest that is on the A1 seat in a PHP variable named "resulted".
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$resulted = mysqli_query("SELECT name FROM guests WHERE seat='A1');
echo $resulted;
?>
I know this is totally wrong but I don't know how i shoud do it....
There is some issue in your code. I have fetched associative array amd print gust name.
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$resulted = mysqli_query($conn, "SELECT name FROM guest WHERE seat='A1'");
if(mysqli_num_rows($resulted) > 0) {
$row = mysqli_fetch_assoc($resulted);
print_r($row['name']);
}
// Free result set
mysqli_free_result($resulted);
mysqli_close($con);
?>
$resulted is a mysqli resource. You need to fetch a row from this resource like this:
$row = mysqli_fetch_assoc($resulted);
echo $row['name'];
For more information, visit http://www.w3schools.com/php/func_mysqli_fetch_assoc.asp.

Need help connecting my database to PHP

I am trying to connect my database to my PHP code using this code:
<html>
<head>
<title>Landing page</title>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<?php
// Check if username and password are correct
if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") {
// If correct, we set the session to YES
session_start();
$_SESSION["logged_in"] = "YES";
echo "<h1>You are now logged in</h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
else {
// If not correct, we set the session to NO
session_start();
$_SESSION["logged_in"] = "NO";
echo "<h1>You are NOT logged in </h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
?>
<p>Public Page</p>
<p>Logout</p>
</body>
</html>
Instead of using the inline username and password, I would like to use the databases username and password from a specific table. I just cant get it to work for some reason, and I am finding it really hard. It would be great if anyone could help.
Note:
You have to establish first a connection to your database. Replace the necessary data inside the connection
I used mysqli_* prepared statement rather than deprecated mysql_*
Replace your if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") { with if($checklog > 0 ){
Code:
/* ESTABLISH FIRST YOUR CONNECTION TO YOUR DATABASE */
$con = new mysqli("host", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT Username, Password FROM user_login WHERE Username = ? AND Password = ?")){
$stmt->bind_param("ss",$_POST["username"],$_POST["password"]);
$stmt->execute();
$stmt->store_result();
$checklog = $stmt->num_rows;
if($checklog > 0){
/* HERE IS YOUR CODE WITH SUCCESSFUL LOGIN */
}
else {
/* HERE IS YOUR CODE WITH UNSUCCESSFUL LOGIN */
}
$stmt->close();
}
There are several ways to connect to MySQL. However, just knowing how to connect isn't enough. You need to learn how to use it as well. Therefor I'm first giving you a couple of links to MySQLi and PDO:
PHP: MySQLi - Manual
PHP: PDO - Manual
Now to answer your question, here are some commonly used methods to connect to mysql:
MySQLi Object Oriëntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
MySQLi Procedural Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_error()){
echo "Failed to connect to MySQL: (" . mysqli_connect_error() . ")";
}
?>
PDO Object Oriëntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>

Trying to print data from my MYSQL database, doesn't show anything nor any errors

I am trying the fetch the data from my database sunypub from the table journal.
Out of many attributes, I am trying to get three atrributes which are of my use on the webpage through PHP, but it is not showing anything on the webpage.
This is the option which is directing to the page display.php, which will show me the attributes value of attribute jname, date and location from the table journal
<div align = "left">
<form action = "display.php">
<input type = "submit" value = "Show all the Conference List">
</form>
</div>
display.php:
<? php
// Create Local variable
$taken = "false";
$database = "sunypub";
$password = "";
$username = "root";
// Connect to database
$con = mysql_connect('localhost', $username, $password, $database) or die ("Unable to connect");
#mysql_select_db($database) or die("Database not found");
echo "Database Connected";
$query = "select * from journal ";
$result = mysql_query($con,$query) or die("Strange Error");
echo "Database Connected";
while( $row = mysql_fetch_assoc( $result, MYSQL_ASSOC ) ){
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
mysql_close($con);
?>
mysql_* is deprecated and is removed in new PHP version. So I highly recommend you to change to PDO or mysqli_* prepared statements, instead of fixing your old code.
So your code could look something like this:
(Note that you have to remove the space here: <? php)
<?php
// Create Local variable
$taken = "false";
$dbhost = "localhost";
$dbname = "sunypub";
$dbpass = "";
$dbuser = "root";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM journal";
foreach($dbh->query($sql) as $row) {
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
$dbh = NULL;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>

Why isn't this php code allowing me to connect to my database?

I'm using a WAMP server and on it I created a database and a table. All the names are correct and the user has full access to everything. When I run the code, it prints out "Unable to select database". Thanks.
<?php
if(isset($_POST["Submit"])){
print_r ($_POST["nutrient"]);
}
session_start();
//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable";
//connect PHP script to database
$connection = mysqli_connect($server, $db_username, $db_password, $database);
//select database to use
#mysql_select_db($database) or die( "Unable to select database");
//$query = "INSERT INTO $table VALUES("")"
//mysql_query($query)
mysql_close();
?>
<body>
</form>
Try something like the following.
<?php
//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable";
//connect PHP script to database
$connection =mysqli_connect("$server","$db_username","$db_password","$database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Your query here
mysqli_close($connection);
?>
I use simple code 1 line. here is my code that i'm using.
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
You went from MySQLI to not using MySQLI in selecting the database as well as the rest of your code.
Try this. I have change mysqli_connect to mysql_connect and mysql_select_db variable.
//connect PHP script to database
$connection = mysql_connect($server, $db_username, $db_password, $database);
//select database to use
$select = mysql_select_db($connection) or die( "Unable to select database");

Categories