HTML Button to Update Mysql table - php

I am trying to UPDATE a row from a MySQL Table with a button in my html page. When i press the button it outputs "Query failed". What should I change to make it work ?
My Html Code:
<form action="status1.php">
<input type="submit" name="approve" value=" + ">
</form>
My Php Code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry="UPDATE applications SET (status) values('1') WHERE today='$today'";
$result = mysql_query($qry);
if($result) {
header("location: applications-admin.php");
exit();
}else {
die("Query failed");
}
?>

You're using the wrong syntax for an UPDATE; it should be something like this:
$qry="UPDATE applications SET status='1' WHERE today='$today'";
HOWEVER
You should look at moving away from the mysql_* functions, as they're being deprecated - you should look at using PDO or mysqli instead.

UPDATE tablename SET fieldname=value WHERE [conditions]

Related

Show all tables within given MySQL database

I'm trying to show all tables within a given MySQL database with php.
I'm very new to all this though and can't find a solution for it. Keeps giving an error 'no found file or directory'.
Anyone who can point out my mistakes here please?
Much appreciated!
<?php include "../inc/dbinfo.inc"; ?>
<html>
<body>
<h2>LIST TABLES FROM DATABASE</h2>
<?php
// Create connection
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
echo "Connection established with the database! </br>";
// SQL to show tables
$sql = "SHOW TABLES FROM paperlessdb";
$result = mysql_query($sql);
if (!$result) {
echo "Database error, could not list tables.\n</br>";
echo 'MySQL error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}
mysql_free_result($result);
?>
First make up your mind, either use mysqli procedural or object orientated. Not a combination of both because its confusing. To avoid that all together use pdo instead.
Now properly connect to the database, you can select the database when connecting to it automatically:
const DB_DATABASE = 'paperlessdb';
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
if($result = $conn->query('SHOW TABLES')){
while($row = $conn->fetch_array($result)){
$tables[] = $row[0];
}
}
print_r($tables);
Use below query,
$sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'paperlessdb'";
We are fetching the data from information_schema db which stores the meta data about our database.
You are using mysqli to connect to the database but use the depreciated mysql to query the database.
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)){}
mysql_free_result($result);
You should use mysqli_query() and mysqli_fetch_array() instead.
It'a a bit more complex but mysql is decrecated and remove as PHP 7 so no choice to jump ahead. Check out PDO ass well. I personally go for mysqli but most say pdo is more intuitive.
It should look more something like:
$result = mysqli_query($conn,$sql);
if(!$result){
die('MySQL error: ' . mysqli_error($conn));
}
while ($row = mysqli_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}

Deleting the row in php

I have create a database (student) and table(details) in SQL, Fields are Name,Class,Section,Address,Mobile. I need delete the Selva row in that table,I can't delete it please explain!!
PHP code-
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
?>
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM details WHERE Name = 'Selva' ");
if($sql) {
header("Location: table1.php");
} else {
echo "ERROR";
}
}
?>
Please explain ! how to delete the row in a table from database.
Your mysql query is proper but you need to check below condition is satisfied or not.
if(isset($_GET['did'])) {
echo 'debug test';exit;
}

Why isn't this echo command being executed?

Please could someone help me understand why the echo command, 'Incorrect Membership Number, please try again.' isn't working?
Everything else seems to be functioning okay.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'DBNAME');
define('DB_USER', 'USER');
define('DB_PASSWORD', 'PASS');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
$mem_no = $_POST['mem_no'];
function SignIn()
{
session_start();
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members where mem_no = '$_POST[mem_no]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if (!empty($row['mem_no'])) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
} // This line is not executing
} else {
echo "Please go back and enter a Membership Number";
}
}
if (isset($_POST['submit'])) {
SignIn();
}
HTML Form as follows:
<form method="post" action="/check.php">
<p>Membership No.</p>
<input name="mem_no" type="text" id="mem_no">
<input name="cat_link" type="hidden" value="https://www.redirectlink.com">
<input name="submit" type="submit" id="submit" value="AELP Member Rate">
</form>
Link to test: https://www.eiseverywhere.com/ehome/index.php?eventid=106953&tabid=239372 and a valid 'Membership Number' is 1234 if you wish to test.
Leaving the form blank does give the correct error message and entering a valid number does redirect me correctly, but inputting an invalid number (9999 for e.g.) doesn't give me the correct output message.
Thank you in advance for any responses.
Regards,
Ash
You need to count rows, because even when a sql query has no results it is not empty. So count it.
function SignIn()
{
session_start();
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members where mem_no = '". $_POST['mem_no'] ."'") or die(mysql_error());
#count rows
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query) or die(mysql_error());
#check count
if ($count != 0) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
}
} else {
echo "Please go back and enter a Membership Number";
}
}
Just a small reminder. mysql_ class in PHP is deprecated and will be removed in the next versions, I suggest you going to use mysqli_ or work with PDO's
Your script is hard to debug for several reasons:
It's unindented (I've fixed that for you in the question)
You're using deprecated mysql functions (see this). Switch to PDO or mysqli.
You have several exit points in your script. Everytime you make a call to the database, you "die" if you fail. that's not good
regardless, I suspect that one of those "die" making your script end prematurely. Instead of using die, handle the errors yourself.
I think this should work:
(Also put error reporting at the top!)
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
session_start();
define('DB_HOST', 'localhost');
define('DB_NAME', 'DBNAME');
define('DB_USER', 'USER');
define('DB_PASSWORD', 'PASS');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
//$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error()); //Useless
$mem_no = $_POST['mem_no'];
function SignIn() {
if (!empty($_POST['mem_no'])) {
$query = mysql_query("SELECT * FROM members WHERE mem_no = '" . $_POST['mem_no'] . "'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
$count = mysql_num_rows($query);
if ($count >= 1) {
$_SESSION['mem_no'] = $row['mem_no'];
header("Location: " . $_POST['cat_link']);
} else {
echo "Incorrect Membership Number, please try again.";
} // This line is not executing
} else {
echo "Please go back and enter a Membership Number";
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
It doesnt make sense to put two else statements in a row. Take the last else block out of the inner if block
if(!empty($_POST['mem_no'])) {
//code
}else{
echo "Please go back and enter a Membership Number";
}
That should execute just fine

No database selected when trying to setup query in php

Ok i get the following error "No database selected" when trying to run a query in php. the connect file in in the connect.inc.php file and that returns no error. i an learning php so any help i thank you. Also to note the query works in phpmyadmin panel with no errors
<?php
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql)) {
echo 'Success.';
} else {
echo mysql_error();
}
?>
The mysql library is deprecated, use mysqli or PDO.
With mysqli, you can also select the database directly when you're creating the connection (and I recommend doing that when possible, if you're only working with one database) :
$db = mysqli_connect("<host>","<username>","<password>","<database>");
Replace <database> with the DB you want to use.
Either use in your connect.inc.php the mysql_select_db function just after mysql_connect:
mysql_select_db('your_database_name');
or add the database name in every query:
$sql = "SELECT `name`, `address`, `city` FROM `your_database_name`.`customers` ORDER BY `id`";
Note that the mysql library is deprecated and you should use mysqli or PDO. If you're learning, run away from any "tutorial" that still uses these deprecated functions.
hope you write write script to connect DB in this way or you can try this....
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
}
}
This is a basic example i have kind of filled in with your code. You will need to fill in the vars with FILL THIS as values.
<?php
$host = "FILL THIS";
$db = "FILL THIS";
$user = "FILL THIS";
$pass = "FILL THIS";
$link = mysql_connect($host,$user ,$pass);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
require 'connect.inc.php';
$sql = "SELECT `name`, `address`, `city` FROM `customers` ORDER BY `id`";
if ($sql_run = mysql_query($sql,$link)) {
echo 'Success.';
} else {
echo mysql_error();
}
mysql_close($link);
?>

Deleting row from a MySQL Table using checkboxes and a button

I want to make a table with the members of a website and in this table when you check the checkboxes and you press the "Delete" button to delete this member from the members table and also to delete his applications from the applications table. With my code when I click the delete button it prints me "Query failed"
This is my code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$data = mysql_query("SELECT * FROM members ") or die(mysql_error());
echo ' <form action="members-exec.php">
<table width="760" border=1>
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<th></th>';
}
echo '
<th>Служител:</th>
<th>Отпуск отпреди 2009год.</th>
<th>Отпуск от мин. год.</th>
<th>Отпуск от тек. год.</th>
</tr>';
while($info = mysql_fetch_array( $data ))
{
echo '
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<td>
<input type="checkbox" name="'.$info['firstname'] .' '.$info['lastname'] .'" value="'.$info['firstname'] .' '.$info['lastname'] .'" />
</td>';
}
echo '
<td>'.$info['firstname'] .' '.$info['lastname'] .'</td>
<td>'.$info['predi'] .'</td>
<td>'.$info['minali'] .'</td>
<td>'.$info['tekushti'] .'</td>';
}
echo' </tr> ';
echo '</table>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<br> <input type="submit" name="remove" value="Delete" /></form>';
}
?>
This is my php part:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" && "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
EDIT:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" ;
$result = mysql_query($qry);
$qry = "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"
&& "DELETE FROM applications WHERE userfname = '$userfname'";
There's your problem - you're trying to do two SQL statements with one call, and mysql_query won't let you do that. It should work if you do two separate queries.
HOWEVER
You should look at moving to mysqli_* or PDO - mysql_* is being deprecated. You can do multiple queries in one call directly using mysqli, too; and they both make use of bound parameters, which helps you write more secure code.
You are trying to execute two delete statements in one query. This is a no-no.
You will need to split the statements into two executes:
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
$result = mysql_query($qry);
$qry="DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
You can always try and use mysqli_multi_query()

Categories