Confusing situation happening when using PHP with Mysqli - php

every time I run this code below:
<?php
$servername = "******";
$username = "******";
$password = "*******";
$dbname = "*******";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date, point, reason, teacher, giver FROM penalty WHERE studentid=".$_GET['id'];
$result = $conn->query($sql);
if ($result["num_rows"] > 0)
{
echo "<table>";
echo "<tr>";
echo "<td>dated</td>";
echo "<td>point</td>";
echo "<td>reason</td>";
echo "<td>giver</td>";
echo "<td>teacher</td>";
echo "</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>".$row["dated"]."</td>";
echo "<td>".$row["point"]."</td>";
echo "<td>".$row["reason"]."</td>";
echo "<td>".$row["giver"]."</td>";
echo "<td>".$row["teacher"]."</td>";
echo "</tr>";
}
echo "</table>";
}
else if ($result["num_rows"] = 0)
{
echo "it is 0!";
}
else
{
echo "Unknown Error!";
}
$conn->close();
?>
I get the error message that I have written like this:
Unknown Error!
So, I'm thinking that the code has some problems in
if ($result["num_rows"] > 0)
What is the problem in the code, and what should I do to solve it?
ps. I'm a newbie in PHP, feel free to answer. Thanks in advance.

To check number of rows return from query we use
$result = $conn->query($sql);
if($result->num_rows > 0)
{
// your code
}
Instead
if ($result["num_rows"] > 0)
Your whole code would be
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr>";
echo "<td>dated</td>";
echo "<td>point</td>";
echo "<td>reason</td>";
echo "<td>giver</td>";
echo "<td>teacher</td>";
echo "</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["dated"] . "</td>";
echo "<td>" . $row["point"] . "</td>";
echo "<td>" . $row["reason"] . "</td>";
echo "<td>" . $row["giver"] . "</td>";
echo "<td>" . $row["teacher"] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "it is 0!";
}
Read http://php.net/manual/en/mysqli-result.num-rows.php
Your code is open for sql injection
Read http://php.net/manual/en/mysqli.prepare.php Prepare statement in mysqli

Related

PHP dropdown inside table

I have a table where all the values are selected from the database, but some cells are empty. How do i put a dropdown list inside that empty cell. The values from the dropdown must come from the database
This is my code:
<?php
include("css/style.php");
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "Iamthebest1009", "dktp");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$dropdown_list = '';
$sql = "SELECT * FROM orden";
$result_list = mysqli_query($link, $sql);
if (mysqli_num_rows($result_list) > 0) {
$dropdown_list = '<select>';
while ($row = mysqli_fetch_array($result_list)) {
unset($id, $name);
$id = $row['id'];
$name = $row['id'];
$dropdown_list .= '<option value="' . $id . '">' . $name . '</option>';
}
$dropdown_list .= '</select>';
}
// Attempt select query execution
$sql = "SELECT * FROM Norm LEFT JOIN Cluster ON norm.cluster_id = cluster.id LEFT JOIN Orden ON norm.orden_id = orden.id ORDER BY norm_name";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<form method="POST">';
echo "<table>";
echo "<tr>";
echo "<th>Norm id</th>";
echo "<th>Norm</th>";
echo "<th>Omschrijving</th>";
echo "<th>Clusteren</th>";
echo "<th>Ordenen</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)) {
if ($row['orden_name']) {
$data_list = $row['id'];
} else {
$data_list = $dropdown_list;
}
echo "<tr>";
echo "<td>" . $row['norm_id'] . "</td>";
echo "<td>" . $row['norm_name'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['cluster_name'] . "</td>";
echo "<td>" . $data_list . "</td>";
echo "</tr>";
}
echo "</table>";
echo '<input type="submit" </input><form>';
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(isset($_POST['submit']))
{
$sql = "INSERT INTO norm (orden_id) VALUES ('$data_list')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close connection
mysqli_close($link);
?>
you can check this code. when $row['cluster_name'] empty then generate dropdown and first create dropdown then check your data exit or not but not tested
<?php
include("css/style.php");
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "Iamthebest1009", "dktp");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$dropdown_list = '';
$sql = "SELECT * FROM orden";
$result_list = mysqli_query($link, $sql);
if (mysqli_num_rows($result_list) > 0) {
$dropdown_list = '<select>';
while ($row = mysqli_fetch_array($result_list)) {
unset($id, $name);
$id = $row['id'];
$name = $row['orden_name'];
$dropdown_list .= '<option value="' . $id . '">' . $name . '</option>';
}
$dropdown_list .= '</select>';
}
// Attempt select query execution
$sql = "SELECT * FROM Norm LEFT JOIN Cluster ON norm.cluster_id = cluster.id LEFT JOIN Orden ON norm.orden_id = orden.id ORDER BY norm_name";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo "<table>";
echo "<tr>";
echo "<th>Norm id</th>";
echo "<th>Norm</th>";
echo "<th>Omschrijving</th>";
echo "<th>Clusteren</th>";
echo "<th>Ordenen</th>";
echo "</tr>";
while ($row = mysqli_fetch_array($result)) {
if ($row['cluster_name']) {
$data_list = $row['cluster_name'];
} else {
$data_list = $dropdown_list;
}
echo "<tr>";
echo "<td>" . $row['norm_id'] . "</td>";
echo "<td>" . $row['norm_name'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $data_list . "</td>";
echo "<td>" . $row['orden_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>

View detailed MySQL Result when Hyperlink is Clicked

I'm trying to achieve the following. On the homepage a MySQL query returns results from table "parcid"(but limited results). The next step is, I would like to hyperlink a field (preferably "ID") to open a new page using the same ID but returning more detailed results. The code below works but obviously I'm missing something somewhere as it is returning all results rather than only results for the clicked on ID. Any help will be greatly appreciated.
Home url: "http://localhost/"
Pdetail url: "http://localhost/pdetail/"
Query on "Home" page
<?php
// set database server access variables:
$host = "localhost";
$user = "root";
$pass = "";
$db = "wordpress";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM parcid";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=1 >";
echo "<tr>";
echo "<td>"."ID"."</td>";
echo "<td>"."City"."</td>";
echo "<td>"."Destination City"."</td>";
echo "<td>"."Weight"."</td>";
echo "<td>"."Length"."</td>";
echo "<td>"."Width"."</td>";
echo "<td>"."Height"."</td>";
echo "<td>"."Type"."</td>";
echo "<td>"."Courier Option"."</td>";
echo "</tr>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo '<td>'.$row[0].'</td>';
echo "<td>" . $row[6]."</td>";
echo "<td>" . $row[12]."</td>";
echo "<td>" . $row[14]."</td>";
echo "<td>" . $row[15]."</td>";
echo "<td>" . $row[16]."</td>";
echo "<td>" . $row[17]."</td>";
echo "<td>" . $row[18]."</td>";
echo "<td>" . $row[19]."</td>";
echo "<td>" . $row[20]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
Query on"pdetailed" page.
<?php
// set database server access variables:
$host = "localhost";
$user = "root";
$pass = "";
$db = "wordpress";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$ID = $_GET['ID'];
// create query
$query = "SELECT * FROM parcid WHERE ID LIKE '%$ID%'";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=1 >";
echo "<tr>";
echo "<td>"."ID"."</td>";
echo "<td>"."CID"."</td>";
echo "<td>"."From"."</td>";
echo "<td>"."Street"."</td>";
echo "<td>"."Suburb"."</td>";
echo "<td>"."Post Code"."</td>";
echo "<td>"."City"."</td>";
echo "<td>"."Province"."</td>";
echo "<td>"."Receiver"."</td>";
echo "<td>"."Destination Street"."</td>";
echo "<td>"."Destination Suburb"."</td>";
echo "<td>"."Destination Postcode"."</td>";
echo "<td>"."Destination City"."</td>";
echo "<td>"."Destination Province"."</td>";
echo "<td>"."Weight"."</td>";
echo "<td>"."Length"."</td>";
echo "<td>"."Width"."</td>";
echo "<td>"."Height"."</td>";
echo "<td>"."Type"."</td>";
echo "<td>"."Courier Option"."</td>";
echo "</tr>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0]."</td>";
echo "<td>" . $row[1]."</td>";
echo "<td>" . $row[2]."</td>";
echo "<td>" . $row[3]."</td>";
echo "<td>" . $row[4]."</td>";
echo "<td>" . $row[5]."</td>";
echo "<td>" . $row[6]."</td>";
echo "<td>" . $row[7]."</td>";
echo "<td>" . $row[8]."</td>";
echo "<td>" . $row[9]."</td>";
echo "<td>" . $row[10]."</td>";
echo "<td>" . $row[11]."</td>";
echo "<td>" . $row[12]."</td>";
echo "<td>" . $row[13]."</td>";
echo "<td>" . $row[14]."</td>";
echo "<td>" . $row[15]."</td>";
echo "<td>" . $row[16]."</td>";
echo "<td>" . $row[17]."</td>";
echo "<td>" . $row[18]."</td>";
echo "<td>" . $row[19]."</td>";
echo "<td>" . $row[20]."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
If you want just the single row identified by $ID then the query is
$query = "SELECT * FROM parcid WHERE ID = '$ID'";
Also when you know you should only receive a single result row from a query, you do not need to run the mysql_fetch_row($result) in a while loop.
Please dont use the mysql_ database extension, it
is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
Unless you are using a framework this statement might be wrong
echo '<td>'.$row[0].'</td>';
Maybe it should be
echo '<td>'.$row[0].'</td>';

PHP - Change only one row, not all

I've just started with PHP and literally been stuck now for 5 hours straight trying to figure this out! I understand what's happening but cannot for the life of me find a fix anywhere D: Basically each row is displayed on the users browser. Beside each one is a 'Mark as complete' button. When this button is pressed is changes the value from 0 to 1. Problem is, it changes the value of 0 to 1 for every row D: Please help me it's a pain in the but now haha! Heres my code:
<?php
// Declare Variables
$host = localhost;
$user = root;
$pass = root;
$db = test;
// Create connection to database
$link = mysqli_connect($host, $user, $pass, $db);
// Check to see if connection was established
if($link === false) {
die("Connection could not be established to database" .mysqli_error());
}
$sql = "SELECT * FROM details WHERE Status = 0";
// Show data
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>First name</th>";
echo "<th>Last name</th>";
echo "<th>Destination</th>";
echo "<th>Value</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<form action='complete.php' method='post'>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Destination'] . "</td>";
echo "<td>" . $row['Status'] . "</td>";
echo "<td>" . "<input type='submit' value='Mark as complete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "No records matching your query were found.";
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
and complete.php
<?php
// Declare Variables
$host = localhost;
$user = root;
$pass = root;
$db = test;
// Create connection to database
$link = mysqli_connect($host, $user, $pass, $db);
// Check to see if connection was established
if($link === false) {
die("Connection could not be established to database" .mysqli_error());
}
// sql to delete a record
$sql = "UPDATE details SET Status=1";
if ($link == true) {
echo "Marked as complete";
} else {
echo "Error updating record: " . $link->error;
}
mysqli_close($link)
?>
You are missing some steps. Here is the full process as you want to do.
Just replace with your. I hope this will solve your problem.
<?php
// Declare Variables
$host = localhost;
$user = root;
$pass = root;
$db = test;
// Create connection to database
$link = mysqli_connect($host, $user, $pass, $db);
// Check to see if connection was established
if($link === false) {
die("Connection could not be established to database" .mysqli_error());
}
$sql = "SELECT * FROM details WHERE Status = 0";
// Show data
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>First name</th>";
echo "<th>Last name</th>";
echo "<th>Destination</th>";
echo "<th>Value</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<form action='complete.php' method='post'>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Destination'] . "</td>";
echo "<td>" . $row['Status'] . "</td>";
echo "<td>" . "<input type='submit' value='Mark as complete'>" . "</td>";
// Put your primary key column name in the place of Id
echo "<input type='hidden' name='user_id' value='".$row['Id']."'>";
echo "</form>";
echo "</tr>";
}
echo "</table>";
}
else{
echo "No records matching your query were found.";
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
and complete.php
<?php
// Declare Variables
$host = localhost;
$user = root;
$pass = root;
$db = test;
// Create connection to database
$link = mysqli_connect($host, $user, $pass, $db);
// Check to see if connection was established
if($link === false) {
die("Connection could not be established to database" .mysqli_error());
}
// sql to delete a record
// Put your primary key column name in the place of Id
$sql = "UPDATE details SET Status=1 WHERE Id='".$_POST['user_id']."' ";
if ($link == true) {
echo "Marked as complete";
} else {
echo "Error updating record: " . $link->error;
}
mysqli_close($link)
?>

mysql_num_rows() returns 0 and I can't figure out why

I don't know where the problem is, that mysql_num_rows() always returns 0.
Here is my code:
$result = mysql_query("SELECT * FROM users WHERE banned='0'");
if(mysql_num_rows($result) == 0) {
die("INTERNAL SERVER ERROR!");
}
while ($array = mysql_fetch_array($result)) {
if(count($array) == 0) {
echo "<tr>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "</tr>";
} else {
echo "<tr>";
echo "<td>" . $array['id'] . "</td>";
echo "<td>" . $array['name'] . "</td>";
echo "<td>" . $array['email'] . "</td>";
echo "<td>" . $array['pont'] . "</td>";
echo "<td>" . $array['rang'] . "</td>";
echo "<td>Bann!</td>";
echo "</tr>";
}
}
My code always returns:
INTERNAL SERVER ERROR!
Why does always my query fails? What is the problem and how can I fix it?
Well since your code doesn't work and you use mysql_* which is deprecated I think it's the best opportunity to change your code to mysqli_* prepared statement or to PDO, they are much safer.
So your code would look something like this:
<?php
$databaseHost = "localhost";
$databaseName = "DBNAME";
$databaseUser = "root";
$databasePass = "";
try {
$dbh = new PDO("mysql:host=" . $databaseHost .";dbname=" . $databaseName, $databaseUser, $databasePass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM users WHERE banned=:bannedState");
$stmt->execute(["bannedState" => 0]);
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<table border='1'>
<?php
if($stmt->rowCount() == 0) {
echo "<tr>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "<td>No Data</td>";
echo "</tr>";
} else {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['pont'] . "</td>";
echo "<td>" . $row['rang'] . "</td>";
echo "<td>Bann!</td>";
echo "</tr>";
}
}
?>
</table>
Side notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
Have error reporting on only while staging, never in production!

MySql no output

Okay, i have this code
<?php
$email = htmlentities($_SESSION['user']['dato'], ENT_QUOTES, 'UTF-8');
$username = "mcnsaoia_onsafe";
$password = "XXX";
$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
$selected = mysql_select_db("mcnsaoia_onsafe",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM users WHERE id= '$email'") or die(mysql_error());
//fetch tha data from the database
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
//close the connection
mysql_close($dbhandle);
?>
but when i run it, it just says Connected to MySQL and it DON'T output anything??
i have no idea why it does that?!
while($row = mysqli_fetch_array($result))
change it with mysql_fetch_array()
while($row = mysql_fetch_array($result))
Check whether rows are returned by your query using mysql_num_rows() function.
if(mysql_num_rows($result)>1)
{
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
}
else
{
echo "No rows found";
}
Note : Use mysqli_* functions . mysql_* functions have been deprecated.

Categories