mysql_query how to display html for if condition - php

So I have this rustic and basic php that will check a value in my database and if its corrects it will pull out the rest of that row I guess but my problem is how to echo certaine html if the result is okay and how to echo some other html if else.
btw atm else is not working, in other words if you input a code that is not on my db it will not show anything
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
}
else {
echo "Im sorry you buddy, you are not a winner this time! $test";
}
mysql_close($connection);
?>

You can use mysql_num_rows(), it's the best way.
if( mysql_num_rows($result) > 0 ){
/* Anything you want here on success */
} else {
/* Anything you want here on failure */
}

if(mysql_num_rows($result) > 0) { echo "output"; } else { echo "error msg"; }

Use mysql_num_rows against the query.
if(mysql_num_rows($result)){ } else { }

Instead of echoing every html value you can simply enclose html in if statements
like:
<?php
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
?>
<b>Hello: <?php echo $name $test"; ?></b>
<?php
}
}
else {
?>
<b> Im sorry you buddy, you are not a winner this time! </b> <?php echo $test";
}
mysql_close($connection);
?>

First you have to correct syntax of database selection like this
mysql_select_db($db_database,$connection);
Insted of
mysql_select_db($db_database);
Check Manual

Related

Established connection to database but rendering a blank page

I am simply trying to display data from a table in my database.
For some reason, it keeps rendering a blank page.
I have no training at all. SO I am sure my code looks like crap. But I can usually get it to work. I researched but all I could find were connection problems. I get a 'connected successfully' message but no data and no error message.
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_pass = '';
$db_name = '';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = "SELECT * FROM `my_table`";
$result = mysql_query("SHOW COLUMNS FROM `my_table`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
mssql_field_name($result,0);
// print_r($row);
}
}
?>
$db_name = ' ' ; is Null write Your Database Name
You should first provide a $db_name, because it's currently blank
$db_pass = '';
you need to provide your database name in here, else your application is literally trying to connect to nothing
You might have to check $mysqli_connect, that the $db_name=''; is null...put your database name inside ''
try like this.
<?php
$conn=mysqli_connect('localhost','root',' ','databasename');
$query="Select * from my_table";
$result = mysqli_query($conn,$query);?>
<table>
<tr>
<th>name</th>
<th>full_name</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["full_name"]; ?></td>
</tr>
<?php
}
?>
Please add your database name and database password, then you can try like this :
$sql = "Select * from table_name";
if ($result=mysqli_query($conn,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
$response[] = $row;
}
} else {
echo 'Could not run query: ' . mysqli_error();
exit;
}
print_r($response);

Retrieving data from MySQL database

Not sure what I'm doing here.
The following code outputs the Database connected statement, but is not displaying any records ("0 results"):
<?php
//Server Details
$host ="localhost";
$user = "X32284679";
$password = "X32284679";
//Connection
$dbc = mysql_pconnect($host,$user,$password);
//Database Selection
$dbname="X32284679";
mysql_select_db($dbname);
if (!$dbc)
{
die("Connection Failed: " .mysqli_connect_error());
}
echo "Connected";
$sql = "select * from staff";
$result = $dbc -> query($sql);
if ($result ->num_rows >0 )
{
echo"<table><tr><th>Email</th><th>Name</th><th>Mobile</th> <th>Address</th><th>Password</th></tr>";
while($row = $result-> fetch_assoc())
{
echo "<tr><td>" .$row["staff_email"]."</td><td>".$row["staff_name"]."</td><td>".$row["staff_mobile"]."</td><td>".$row["staff_address"]."</td><td>".$row["staff_password"]."</td></tr>";
}
echo "</table>";
}
else
{
echo "0 Results";
}
$dbc->close();
?>
this looks like a whole lot of copy & paste from tutorials.
The use of both mysql_ and mysqli_ functions is pretty much useless all together..
As it look slike you want it in mysql_ ive re written your code to fit your needs.
Code:
<?php
//Server Details
$host ="localhost";
$user = "X32284679";
$password = "X32284679";
//Connection
mysql_connect($host,$user,$password) or die("An error occured while connecting...");
//Database Selection
$dbname="X32284679";
mysql_select_db($dbname);
$sql = "select * from staff";
$Query = mysql_query($sql);
if (mysql_num_rows($Query)){
$html .= "<table><tr><th>Email</th><th>Name</th><th>Mobile</th> <th>Address</th><th>Password</th></tr>";
while($row = mysql_fetch_array($Query)){
$html .= "<tr><td>" .$row["staff_email"]."</td><td>".$row["staff_name"]."</td><td>".$row["staff_mobile"]."</td><td>".$row["staff_address"]."</td><td>".$row["staff_password"]."</td></tr>";
}
$html .= "</table>";
}
else{
$html .= "0 Results";
}
echo $html;
mysql_close();
?>

How to delete a record from mysql using a button?

I would like to be able to delete a row using the delete-button I display at the end of each row. I need two queries to delete a person from my database completely since I have a n-m relationship between Persons and Functions.
The queries are as follows:
delete from `Persons` where `Person ID` = '1';
I would like to implement these queries using the delete-button provided in the actual code, how can I do this?
UPDATE:
I made changes according to what Kristian Hareland wrote, and it reloads but the person isn't deleted, what should be changed to make it work?
showall.php:
<table>
<thead>
<tr>
<?php
// Variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$query = "SELECT p.`Person ID`, p.`First Name`, p.`Last Name`, p.Gender, p.`Date Of Birth`, p.Email, p.`Phone Number`, c.Region, c.Country, p.`Delegation ID`
FROM Persons as p, Chapters as c
WHERE c.`Chapter ID`=p.`Chapter ID`
ORDER BY p.`Delegation ID";
$result = mysql_query($query) or die($dberror3 . mysql_error());
$row = mysql_fetch_assoc($result);
foreach ($row as $col => $value) {
echo "<th>";
echo $col;
echo "</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
DeletePerson.php:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
$Del = mysql_query("DELETE FROM `Persons` WHERE `Person ID` = '$UserId'");
if($Del){
$Flag = TRUE;
}
else{
$Flag = FALSE;
}
header("Location: /showall.php?delete=$Flag");
}
else{
die("Error");
}
I would use JavaScript and Ajax here.
Make a Html-button with an onclick function like delete_user();
delete_user() calls a .php file to validate the rights and execute some mysql-delete promts.
The .php file returns a boolean to the JavaScript.
You could catch that boolean up and inform the user about the result.
IMHO best way is create separate file functions.php
<?php
//functions.php
$id = filter_this($_POST[id]);
mysql_query("delete from Persons_Functions where `Person ID` = '$id');
?>
and send there via JQuery:
function deleteuser(id){
$.post("admin_action.php", {action:'delete_user',id:id}, function(data){
if(data.trim()=="done"){
console.log("OK!");
});
}}
Without JS You can use HTML (just change BUTTON to A):
<a href='script.php?action=delete&id=12'>DELETE</a>
and PHP:
$id = $_GET[id];//filter this value
mysqli_query($link, "DELETE FROM users WHERE ID='$id'"); //use mysqli
I would use the GET method for this
<?php foreach ($results as $result): ?>
Delete
<?php endforeach; ?>
At the top of index.php
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
if (isset($_GET['id']) && intval($_GET['id']) != 0) {
$id = intval($_GET['id']);
$stmt = "delete from table where id='{$id}'";
}
}
Just use a link:
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
</tbody>
DeletePerson.php:
<?php
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
mysql_query("DELETE FROM Persons WHERE Person ID = '$UserId'");
mysql_query("DELETE FROM Persons_Functions WHERE Person ID = '$UserId'");
header("Location: /showall.php?flag=deleted");
}
else{
die("Error");
}

mysql_fetch_array($result) echo $rows in html

So I have these specific rows that I'm pulling if a code matches the database but I have no idea on how to echo this to my full html, is there anyway to make this $rows a $_POST or $_get to html?
thanks
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
} else {
echo "error msg";
}
mysql_close($connection);
?>
You just need to update your while loop
Following code is to create your result Array, by that result array you can use the values in HTML too.
$resArr = array();
while($row = mysql_fetch_array($result)) {
$resArr[] = $row;
}
echo "<pre>";print_R($resArr);exit;
try
$query = "SELECT * FROM '$table' WHERE '$field' = '".$_GET["qcode"]."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_assoc($result))
{
$name1 = $row[$field];
$test1 = $row[$test];
echo "Hello:" .$name1. $test1;
}
}
else { echo "error msg"; }
Also use mysql_real_escape_string() to prevent sql injection or better to use mysqli or PDO
You have two alternatives :
i) Use a .php file and write the html part there. This way you run php code with simple, php tags and display stuff where you need.
example :
Create a file called test.php and put this code in it and run.
</head>
<body>
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database,$connection)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "<p>".$name." ".$test."</p>";
}
}
else { echo "error msg"; }
mysql_close($connection);
?>
</body>
</html>
This example puts the content in a paragraph in the html.
ii) echo the content from php by encoding it JSON and receive it using jquery from your html form. I'll not elaborate on this since it is not in the scope of the question.
And DO REMEMBER TO USE THE mysql_real_escape_string() to keep your code robust and prevent sql injection.

mysql_query SELECT do not give the desired result

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Categories