Mysqli wont allow table's to show when called on - php

As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`

Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>

Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>

Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>

Related

Load MySQL Data into Corresponding PHP Variables

I got this work for me, but I'm sure there's a better way to get this done. But, I've searched many hours without finding the exact answer to what I'm looking to do. Basically getting the variable usrID from the URL, I need to search MySQL for the corresponding information to this user. Later I want to use the different fields on my page (better website) to personalize the experience.
<?php
$servername = "localhost";
$username = "authorized-user";
$password = "secret";
$dbname = "agentDB";
$usrID = "001";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$Lname = $row["Lname"];
$Fname = $row["Fname"];
$tl = $row["tl"];
}
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load MySQL Data into Corresponding PHP Variables</title>
</head>
<body>
here is the body<br>
My name is: <?php echo $Fname; ?> <?php echo $Lname; ?><?php echo $tl; ?>
</body>
</html>
You could create a variable to store a full name and then "tl" on it like this:
$user_info = $Lname . ", " . $Fname . ": " . $tl;
Then:
<?php echo $user_info; ?>
Wherever you need that information.
If you want to minimize the amount of variables being assigned you could wrap it in a function and return the desired data field:
function fetchUserData(userData) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userData = $row[userData];
}
}
return $userData;
}
mysqli_close($conn);
You can the get the specified data like this:
<?php echo fetchUserData("Fname"); ?>

How to show table from MySQL database using php and html

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!
Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.
I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

php read data from sql database

I'm trying to learn php and I can't read any data from my database!. I know the connection to the server is live and working but this line seem to be giving me problems.
$result = $conn->query($sql);
Where $sql = "SELECT firstName, middleName, lastName FROM Base";
I'm not sure what the problem is but any hints or answer are appreciated .
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My first PHP page</h1>
<?php
// connect to database
$user_name = "superUser";
$password = "";
$database = "Base"$server = "127.0.0.5";
// open connection to the server
$conn = new mysqli($server, $user_name, $password);
// echo "Connection to the server is open";
// check connetion
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
print "Connection to the server is open";
}
// load the data from the table
$sql = "SELECT firstName, middleName, lastName FROM Base";
// echo $conn->server_info;
$result = $conn->query($sql);
if ($result) {
echo "Table was found";
}
else echo "no";
/*while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br />";
}
print $result["firstName"];// ": Number of Rows!" ;*/
// if ($result->num_rows > 0) {
// output data of each row
// close server connection
$conn->close();
?>
</body>
</html>
The following is a mysqli connect example.
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You forgot to add your database name.
Change this,
$conn = new mysqli($server, $user_name, $password);
to this
$conn = new mysqli($server, $user_name, $password, $database);

How to enter a server IP into a mysql table?

I want to create a page which displays no of times visited and all the IP addresses visiting the web page.
For that I created a mysql table which displays new IP in a new row, but I am unable to execute it.
Most likely, the error is in entering server ip into the table.Here's the full code:
<html>
<head>
<title>Delta sys ad task3</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'prabakar';
$dbpass = 'praba1110';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('server_IPs', $conn);
echo mysql_errno($conn) . ": " . mysql_error($conn). "\n";
$counter=1;
$flag=0;
$sql='SELECT * FROM IPs';
$retval = mysql_query( $sql, $conn );
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if($_SERVER[SERVER_ADDR]==$row['ip'])
break;
else
$flag=1;
}
if($flag==1)
{
$sql="INSERT INTO IPs VALUES('$_SERVER[SERVER_ADDR]')";
$retval = mysql_query( $sql, $conn );
}
echo mysql_errno($conn) . ": " . mysql_error($conn). "\n";
$counter++;
print "No of times site visited: $counter
IP Adresses visited:";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
print "$row['ip']";
}
mysql_close($conn);
?>
</body>
</html>
You need to remove the extra quote:
Change
('$_SERVER['SERVER_ADDR']')
to
('$_SERVER[SERVER_ADDR]')

What is wrong with the SQL Syntax in this PHP code?

I am learning PHP so I was practicing SQL and CRUD in PHP however I seem to have an issue but I don't see what is wrong. There are two files:
databases.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
<ul>
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// Output data from each row
?>
<li><?php echo $subject["menu_name"] . " (" .$subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
and databases_update.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Often these are form values in $_POST
$id = 5;
$menu_name = "Delete me";
$position = 4;
$visible = 1;
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if ($result) {
// Success
// redirect_to("somepage.php");
echo "Success!";
} else {
// Failure
// message = "Subject creation failed";
die("Database query failed. " . mysqli_error($connection));
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
The error I am receiving is when I go to localhost:8888/databases_update.php.
This is the error:
Database query failed. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 5' at line 1
What is causing this?
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
is the problem where there is a comma preceding the "WHERE" keyword.
visible = {$visible}, WHERE id = {$id}
The answer by Wallyk is correct. However it would be better (safer!) to use prepared statements as they prevent SQL injection by improper escaping.
What you then need to do is use the mysqli_prepare function (or $connection->prepare()), then bind the required parameters to the query, and execute it. Like so:
Replace:
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
$result = mysqli_query($connection, $query);
With:
$query = $connection->prepare("UPDATE subjects SET menu_name=?, position=?, visible=? WHERE id=?");
$query->bind_param('siii', $menu_name, $position, $visible, $id); // siii means 1 string, followed by 3 integer values
$result = $query->execute(); // actually run the query

Categories