Call to DB to check if a value exists - php

I'm trying to run a query to check if what is entered into a textfield matches that of what is stored in a database.
The current code:
</form>
<br />
<h2>Discount Code</h2>
<br />
<form method="POST" action=''>
<input type="text" name="discount" />
<input type="submit" name="discountSubmit" value="Apply" />
<?php
if(isset($_POST['discountSubmit'])){
$discountCode = $_POST['discount'];
$codeCheck = mysqli_query("SELECT code FROM discount WHERE code = $discountCode");
var_dump($codeCheck);
}
?>
</form>
However, upon clicking discountSubmit the var_dump returns NULL so it would lead me to assume $codeCheck is wrong, however it looks right to me.
I connect through the database through another page so the issue doesnt lie there
Database Structure:
id code discount expire
1 WEB10 10.00 2013-06-01
Expire isn't relevant just at the moment.

Here, code is not an integer value. Hence, enclose it by single quotes. You should also include the $conn (connection variable) while using mysqli_query() statement - mysqli_query()
$codeCheck = mysqli_query($conn, "SELECT code FROM discount WHERE code = '$discountCode'");
[EDIT]
If you are including the connection page inside this page, try doing these:
connect.php
function connect(){
$conn = mysqli_connect($host, $un, $pw, $db);
return $conn;
}
Now, call this function from the current page and get the connection variable:
$conn = connect();
Now, use $conn for the mysqli_query() function.
Change the if condition as follows:
if(isset($_POST['discount']))

You shouldn't mix SQL with HTML
You shouldn't use a function without reading its manual page first
You shouldn't use bare API with mysqli, but some abstraction library instead.
A better version for your code, courtesy of safeMysql which works the natural way you expect from mysqli_query but don't get it.
<?php
$check = NULL;
if(isset($_POST['discountSubmit']))
{
$sql = "SELECT code FROM discount WHERE code = ?i";
$check = $db->getOne($sql, $_POST['discount']);
}
?>
<h2>Discount Code</h2>
<br />
<form method="POST" action=''>
<input type="text" name="discount" />
<input type="submit" name="discountSubmit" value="Apply" />
</form>
<?php var_dump($check); ?>

Related

PHP query for copying tables

This has to be somewhere online but I am having no luck after hours of trying to do this.
So I've HTML form on one page and a PHP page that creates a database fine..
<form action="createdb.php" method="post">
<label for="dbname"><b>Name of DB</b></label>
<input type="text" name="dbname" id="dbname"/>
<input type="submit" value="Create DB">
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname = $_POST['dbname'];
if (mysqli_query($conn,"CREATE DATABASE $dbname")) {
echo "Database created";
} else {
echo "Database was not created";
}
mysqli_close($conn);
?>
Then I have underneath the PHP code these forms.. The form for creating the tables work fine within the DB that has just been created.. But its the form for copying tables from a DB already created into the newly created DB.
<form action="createtable.php" method="post">
<label for="tablename"><b>Create Table within new DB</b></label>
<input type="text" name="tablename" id="tablename"/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Create Table">
</form>
<p>OR</p>
<form action="copytables.php" method="post">
<label for="tablename"><b>Copy RSS Tables</b></label>
<input type="text" name="tablename" id="tablename" readonly/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Copy Tables">
</form>
I wanted to copy the tables, structure and data called 'lookup_age' and 'score' into the new DB from a database called 'rss_db'. I've rewrote the PHP page needed in many different ways and ATM it has been left like this, as of something I seen on W3schools, which confused me even more. I know it can be easily done via PHPMYADMIN but need it through a query now and HTML form if possible. Heres what I have as followed but wondering what should the query line actually be if possible..
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname =$_POST['holdname'];
mysqli_select_db($conn,"$dbname");
mysqli_select_db($conn,"rss_db");
$sql = "
INSERT lookup_age
INTO $dbname
FROM rss_db";
mysqli_close($conn);
?>
I don't know if these will help but you could try:
create table `table2` like `table1`;
insert `table2` select * from `table`;
or, as a single line perhaps
create table `table2` as select * from `table1`;
try this query, to copy the tables:
$sql = " create table '$dbname' as select * FROM 'rss_db'";
FINALLY FOUND IT!! As simple as...
$query = "INSERT INTO $dbname.lookup_age
SELECT * FROM rss_db.lookup_age";

How do I add a row to mySQL using PHP?

I am trying to add an "admin" section of my website. Right now I am working on a section to add a new row to my MySQL database.
The first file is my admin.php:
<html>
...
<body>
<form action="add.php" method="post">
<input type="text" name="order" />
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
</body>
</html>
My goal here is to add 2 pieces of data (the table only has 2 columns right now) to the new row.
Then, I have my add.php file:
<?
//declare my connection variables - I'll move these to a secure method later
mysql_connect($servername, $username, $password) or die (mysql_error ());
// Select database
mysql_select_db($dbname) or die(mysql_error());
// The SQL statement is built
$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='admin.php'>Back to main page</a>";
}
else {
echo mysqli_errno($this->db_link);
}
?>
<?php
// close connection
mysql_close();
?>
Anytime i input any data (non-duplicate of what is already in the table), it gives me an error. If I clear my table completely of all data, it will input once. I am getting a duplicate key error, but my key should be "orders", which is unique every time I input it.
Suggestions?
If you are actually inserting a new row, you shouldn't fill the ID yourself but rather set it as AUTO_INCREMENT in your database. And then, have you form as such:
<form action="add.php" method="post">
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
And your PHP code like so:
$newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable
$sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')";
$result = mysql_query($sql) or die('Failed executing query: '.mysql_error());
AUTO_INCREMENT can be set up in phpMyAdmin with the following query:
ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT;
Finally, don't use mysql_* functions, they are deprecated.
I am guessing the 'id' field of your table is a primary key. If that's the case, you cannot have two rows that have the same identifier.
By your variable name newstatus, it seems to me like you're trying to update the status of an order ; is it the case? If yes, you should use a UPDATE SQL query of the form:
UPDATE table SET status='somestatus' WHERE id=someid

echoing data from mysql_fetch_array

I'm trying to display data from my database table selected from a 'date'.
The query executes, but when I echo I don't get any result. Could you please help me with this?
<?php include 'includes/connection.php'; ?>
<html>
<head>
<title> </title>
</head>
<body>
<?php
if(isset($_POST['submitted'])){
$sql = "SELECT * FROM dagtaken WHERE datum = $_POST[datum]";
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($result)){
echo $row['aantal'];
}
}else{
?>
<form action='' method='POST'>
<p><input type="date" name="datum"></p>
<p><input type='submit' value='Dagtaak toevoegen' />
<input type='hidden' value='1' name='submitted' /></p>
</form>
<?php } ?>
</body>
</html>
The query shouldn't execute, since dates are very obviously strings and require quotes. That said...
Try this:
mysql_query("SLEECT * FROM `dagtaken` WHERE `datum`='".mysql_real_escape_string($_POST['datum'])."'");
Now on to the actual problem, you are checking if(isset($_POST['submitted'])), but nowhere do I see <input name="submitted" in your source (EDIT Never mind, it has a stupid amount of whitespace pushing it off the edge). Try if(isset($_POST['datum'])), since that's the variable you actually use.
You haven't named your submit button, so your PHP code never kicks in. Don't check for form fields when all you really need is to check if a POST has occured.
Quick fix for you code:
<input type="submit" name="submitted" value="Dagtaak toevoegen" />
^^^^^^^^^^^^^^^^^
Better fix:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
your code here ...
}
First, Escape your data. SQL injection is now very easy
Second, do you have data in your database?
Try print_r($row) instead of echo $row...
$_POST is with quotes...=> $_POST["datum"]
Last addition, is your date the same as your input?

How can I check if a MySql field is equal to 1?

I'm creating a forum in PHP and using MySql as a database, and was wondering how I could check if a MySql field topic_locked was equal to 1. If it isn't, the reply code would be displayed. How can I check this, and if you can help me find how to check this, how could I set it to 1 through the forum?
I dont know your code. But I am sharing simple program to check a mysql field's value.
<?php
// Database select and connect to host
$sql= mysql_query("SELECT topic_locked FROM table WHERE Id='your_id'");
$res= mysql_fetch_array($sql);
$value= $res['topic_locked'];
if($value=='1')
{
// reply code
}
?>
Update asked,
<?php
if(isset($_POST['update']))
{
$id= $_POST['id'];
//Database select and connect to host
mysql_query("UPDATE table SET topic_locked='1' WHERE Id='$id'");
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="your_id" />
<input type="submit" name="update" />
</form>

Setting value in mysql table using html button

I got a table with dynamic data with 5 td-s. First one is for the ID, second one for date, third for the name of the author, fourth for some properties and in the last one i got two buttons. I want them to change the value of the $status in applications table. For that I made 2 php files in which I added the mysql update function for each of the buttons. But I don't know why when I press the buttons it does everything in the php except it doesn't change the value of $status. Please let me know where I am wrong and how can I make it work. Thanks in advance.
The html code of the buttons (the last td):
<form action="status1.php">
<input type="submit" name="approve" value=" + ">
</form>
<form action="status2.php">
<input type="submit" name="refuse" value=" - ">
</form>
The PHP code for the buttons - status1.php (status2.php is the same but it changes the $status value to 2 instead of 1)
<?php
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_query('set names windows-1251', $link);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$id=$_GET['id'];
$qry="UPDATE applications SET status=1 WHERE id='$id'";
$result = mysql_query($qry);
if($result) {
header("location: applications.php");
exit();
}
else {
die("Query failed");
}
?>
You are using $_GET['id'] as identifier, but as far as I can see in the code, you are not actually sending any GET information apart from the submit button itself. So your query is currently actually updating the row WHERE id=''. That's why you don't get errors, but you don't get your desired result either.
Change the action parameter of your form to status1.php?id=$id, or add something like <input type="hidden" name="id" value="$id"/> inside the form.
Well, are you getting any errors? Comment out the header("location: applications.php"); line so you will see if it throws any. Also try adding something like echo $qry so you can visually verify that the query is correct.
Also, you should read up on SQL injection and how to protect against it. Directly sticking user input into the query like that can open the door to nastiness. Also, you aren't checking user input for apostrophes which can break your query. I personally use PDO, which makes it a lot easier and a bit safer.
Another suggestion, rather than having to maintain two separate submission PHP files, just put your two submit buttons like this:
<input type="submit" name="status" value=" + ">
<input type="submit" name="status" value=" - ">
Then change the form action to the name of the consolidated php file and in that file, just evaluate the value of the status like:
$status = 0;
if ($_GET["status" == " + ") $status = 1;
If you install PDO, you'd do the meat of the DB update like this:
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_DATABASE, DB_USER, DB_PASSWORD);
$sql = $pdo->prepare("UPDATE applications SET status=? WHERE id=?");
$sql->execute(array($status, $_GET["id"]));
..which would be a little safer than what you're doing now.
Disclaimer: I'm just a hobbyist PHP programmer, so there may be better ways than I've mentioned :)
use this instead of ur form tag
for form 1
<from method="get" action="status1.php">
<input type="hidden" name="id" value="1"/>
<input type="submit" name="approve" value=" + "/>
</form>
for form2
<from method="get" action="status2.php">
<input type="hidden" name="id" value="2"/>
<input type="submit" name="refuse" value=" - "/>
</form>

Categories