Very basic newbie question please; I've managed to retrieve single fields and pull them through to a webpage; but am really struggling to get my head around what's required to show the contents of a table using mysqli.
I get the sense I'm not using the correct type of loop as I'm only seeing the first record in my table repeating infinitely across the page; so if anyone could provide me with the correct syntax to handle requests of this nature I'd be most grateful.
Many thanks!
<?php
require_once ("functions.php");
require_once ("connection.php");
session_start();
?>
<html>
<head>
<title>My Team</title>
<script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>My Team</h1>
<hr />
<?php
if (logged_in() == false) {
redirect_to("login.php");
}
else {
if (isset($_GET['User_ID']) && $_GET['User_ID'] != "") {
$id = $_GET['User_ID'];
}
else {
$id = $_SESSION['User_ID'];
}
// # connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// # query database
// fetch data from mysql database
$sql = "SELECT a.*, b.*, c.* FROM Users a inner join Teams b on a.User_ID=b.User_ID inner join Players c on b.Team_ID=c.Team_ID WHERE a.User_ID = {$id}";
if ($result = $mysqli->query($sql)) {
$user = $result->fetch_array();
}
else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
// echo the user profile & team data
echo "<p>Coach: {$user['Username']}</p>";
echo "<p>Team: {$user['Team_Name']}</p>";
// echo the player data in table
while ($row = $user) {
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
// showing the login & register or logout link
if (logged_in() == true) {
echo 'Log Out';
}
else {
echo 'Login | Register';
}
?>
<hr />
</body>
</html>
That's because you're fetching the result from database only single time with following code.
$user = $result->fetch_array();
You should use $result->fetch_array() in while loop to run through all the records of database like this,
if ($result = $mysqli->query($sql)) {
while ($row=$result->fetch_array()){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
So your while loop will come inside the if condition.
Your final code will look something like this,
<?php
require_once ("functions.php");
require_once ("connection.php");
session_start();
?>
<html>
<head>
<title>My Team</title>
<script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>My Team</h1>
<hr />
<?php
if (logged_in() == false) {
redirect_to("login.php");
}
else {
if (isset($_GET['User_ID']) && $_GET['User_ID'] != "") {
$id = $_GET['User_ID'];
}
else {
$id = $_SESSION['User_ID'];
}
// # connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// # query database
// fetch data from mysql database
$sql = "SELECT a.*, b.*, c.* FROM Users a inner join Teams b on a.User_ID=b.User_ID inner join Players c on b.Team_ID=c.Team_ID WHERE a.User_ID = {$id}";
if ($result = $mysqli->query($sql)) {
while ($row=$result->fetch_array()){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
// echo the user profile & team data
echo "<p>Coach: {$user['Username']}</p>";
echo "<p>Team: {$user['Team_Name']}</p>";
// Place above couple of codes accordingly.
}
// showing the login & register or logout link
if (logged_in() == true) {
echo 'Log Out';
}
else {
echo 'Login | Register';
}
?>
<hr />
</body>
</html>
Use you while loop as
while ($row=$result->fetch_array){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
Related
I am trying to display information regarding the user after they have logged in. After the user has logged in the user will be redirected to success.php. I use MySQL and a form is an HTML form.
I tried writing the success page in two different ways
success.php (1)
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
include ("getUser.php");
// header("Location: getUser.php");
echo "done";
}
success.php (2)
<?php
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
echo "done";
}
?>
<h2>you have logged in</h2>
<p><?php include ("getUser.php");?></p>
I tried to include a file getUser.php that is suppose to retrive everything regarding the user.
getUser.php
$username = mysqli_real_escape_string($connection, $_REQUEST['username']);
$sql= "select * from userTable where username = '$username'";
if($result = mysqli_query($connection, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<table";
echo "<tr>";
echo "<th>username</th>";
echo "<th>city</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No user" . mysqli_error($connection);
}
}
I keep getting the "No user" error message from the getUser.php. I do not understand why I get it
In getuser.php you didnt make connection with your database.So add the below line at top of your php document.
$connection = new mysqli("HOST_NAME","USER_NAME","PASSWORD","DATABASE_NAME") or die("Connect failed: %s\n". $connection -> error);
This more than likely will not solve your issue but I believe it could lead you closer or help us better understand what is going on. I can't comment yet so I am posting it here and will continue to help you along until we solve the problem.
Add this to the top of your php documents:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
It will write errors to a text document stored on your server to help us debug your issue.
This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
Closed 1 year ago.
I am new to php coding.
I am adding each row delete button, but it should not working.
This is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM venu ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
<th>rollnumber</th>
<th>address</th>
<th>phonenumber</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><form action='delete.php' method='POST'><input type='hidden' value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
This is my delete code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$name = $_POST['name'];
$id = $_POST['id'];
$rollnumber = $_POST['rollnumber'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
if($name!='' and $id!='')
{
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>
I am trying to delete each row using a button, but it is not working.
In your html view page some change echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>"; like bellow:
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>";
echo "</tr>";
}
?>
PHP delete code :
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM venu WHERE id = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
} else {
echo "ERROR";
}
}
?>
Note : Please avoid mysql_* because mysql_* has beed removed from
PHP 7. Please use mysqli or PDO.
More details about of PDO connection http://php.net/manual/en/pdo.connections.php
And more details about of mysqli http://php.net/manual/en/mysqli.query.php
First you need to change your button like
echo "<td>Delete</td>";
this will send the ID of the row which you want to delete to the delete.php
Secondly you need to change a bit your delete.php currently is wide open for SQL injections. Try using MySQLi or PDO instead
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM venu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
}
Of course if you need to add more parameters in delete query you should pass them also with the button..
EDIT: Simple example for update record
You can put second button on the table like
echo "<td>Update</td>";
Then when you click on it you will have the ID of the record which you want to update. Then in update.php
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param('sisi', $name, $rollnumber, $address, $id);
$stmt->execute();
$stmt->close();
}
Here ( in update.php ) you can have form which you can fill with new data and pass to variables $name, $rollnumber, $address then post it to update part.
Something to start with: PHP MySqli Basic usage (select, insert & update)
change up your query to use the dynamic value entered by the user, right now it is hard coded in there.
session_start();
require_once 'conn.php';
class myClass extends dbconn {
public function myClassFunction(){
try {
$id = $_GET['id'];
if(isset($_GET['id'])) {
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $this->connect()->query($sql);
$stmt->bind_param('i', $id);
header("location: ../filepath/index.php");
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
}
This line is wrong, you need to set the WHERE clause to the data you get from the hidden input value
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
Should be:
$sql = mysql_query("DELETE FROM 'venu' WHERE address='"._POST['address']."'");
And in the little form you are using, change:
<input type='hidden' value='".$row["address"]."'/>
to:
<input type='hidden' name='address' value='".$row["address"]."'/>
I have made a SQL command line interface for my own purpose and testing with the following code:
input.php
<!DOCTYPE html>
<html>
<body>
'DESC'command under dev...
<form action="output.php" method="post">
<textarea name="query"></textarea>
<input type="submit">
</form>
</body>
</html>
output.php
<!DOCTYPE html>
<html>
<body>
<div>
<?php
$servername = "server_name"; //I do not wish to show my credentials
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = $_POST["query"];
$result = $conn->query($sql);
if ($result === TRUE) {
if (substr($sql, 0, 6) == "SELECT") {
//Initialize table
echo "<table class=\"table\">";
echo "<tr><th>ID</th><th>Username</th><th>Password</th><th>Email</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"]. "</td><td>" . $row["password"]. "</td><td>" . $row["email"] . "</td></tr>";
}
echo "</table>";
echo "<code>" . $result->num_rows . " rows selected</code>";
} elseif (substr($sql, 0,11) == "INSERT INTO") {
echo "Inserted. Command: $sql";
} elseif (substr($sql, 0, 6) == "DELETE") {
echo "Deleted. Command: $sql";
} elseif (substr($sql, 0, 6) == "UPDATE") {
echo "Updated. Command: $sql";
} else {
echo "Code under dev...\nSorry!";
}
} else {
echo "ERROR: " . $conn->error;
}
echo "<br>";
?>
</div>
</body>
</html>
I have checked the database credentials; they're all fine- no conn error.
I know this because I worked with a table with some data before.
Now, on entering a query, nothing happens except it leaves a message- 'ERROR: '.
Please inform me of any errors.
The query() function only returns TRUE when called with a SQL-statement that doesn't affect rows. In all other cases it returns an object of the type mysqli_result().
That causes the if ($result === TRUE) to jump to else and display the error. In fact there was no error, as $result probably holds a result object.
Try to confirm this by adding echo $result->num_rows; to your else clause.
mysqli::query
See the mysqli::result documentation for more information on how to process your query results.
I am using this code which allows me to see my DB records in a table and in this table there is an option to delete or edit the records.
Only I get this error message and I can't figure out what I am doing wrong.
The error message:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\Inventaris++\NinjaCodeDelete.php on line 32
The code:
<?php
include'Connect2db3.php';
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM BCD WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
$query = "SELECT ID, Categorie, SerieNummer, MacAdress, ProductCode, Prijs, RekNummer, PaletNummer, Hoeveelheid, Aantekeningen FROM BCD";
$stmt = $conn->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
echo "<a href='reports.php'>View Reports</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
echo "<tr>";
echo "<th>Categorie</th>";
echo "<th>SerieNummer</th>";
echo "<th>MacAdress</th>";
echo "<th>ProductCode</th>";
echo "<th>Prijs</th>";
echo "<th>RekNummer</th>";
echo "<th>PaletNummer</th>";
echo "<th>Hoeveelheid</th>";
echo "<th>Aantekeningen</th>";
echo "</tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$Categorie}</td>";
echo "<td>{$SerieNummer}</td>";
echo "<td>{$MacAdress}</td>";
echo "<td>{$ProductCode}</td>";
echo "<td>{$Prijs}</td>";
echo "<td>{$RekNummer}</td>";
echo "<td>{$PaletNummer}</td>";
echo "<td>{$Hoeveelheid}</td>";
echo "<td>{$Aantekeningen}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){
window.location = 'NinjaCodeDelete.php?action=delete&id=' + id;
}
}
</script>
I also want to say that I am not an advanced programmer I found this code online, where it seemed to be working for the other people who have used it.
I have some experience with Mysql and php but not with PDO.
I hope u can help me!
thank you in advanced.
What is inside your " include'Connect2db3.php'; "?
And with this I'm refering to connect2db3.php and is this file inside the right folder?
Your connection could look like this:
<?php
$config['conn'] = array(
'host' => 'yourHostName',
'username' => 'yourUserName',
'password' => 'yourPassword',
'dbname' => 'yourDBName'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
?>
I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}