Validate Promo Code for one time use PHP/My SQLi - php

I’m very new to the whole MySQLi thing. I have a basic understanding of PHP. Anyway, I’ve searched around here and just haven’t been able to get a solid answer.
Basically, I have a form where a person can enter name, email and promo code. The form validates the name and email but when it comes to the promo code, that’s where I’m getting stuck.
I have a database that has two columns. One is for the codes and the other is for a “used” column – eventually I need to be able to write a “1” to that column when a unique code has been used so it cannot be used again. I’m trying to use some code I found on here, FYI.
Here is the PHP (after connecting) to the database:
if(isset($_POST['sponsorcode']) && !empty($_POST["sponsorcode"])){
$sponsorcode = mysqli_real_escape_string($link,$_POST['sponsorcode']);
$query = "SELECT 'sponsorcode' FROM 'teachercodes' WHERE sponsorcode = '$sponsorcode'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$option = "";
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)) {
$option = "<option value='{$row['codes']}'>{$row['codes']}</option>";
}
Any tips would be GREATLY appreciated! Thanks.

No reason to perform your task as two separate steps. Simply mark the sponsor code as used in the teachercodes table. If the update affected any rows (i.e. mysqli_affected_rows returns 1 or more) then it hasn't been used before and is a valid sponsor code. Something like this:
// Make sure a sponsor code was provided
if (isset($_POST['sponsorcode']) && !empty($_POST['sponsorcode'])) {
// Escape the sponsor code to prevent SQL injection
$code = mysqli_real_escape_string($link, $_POST['sponsorcode']);
// Mark sponsor code as used if possible
$sql = 'UPDATE teachercodes SET used=1 WHERE sponsorcode="' . $code . '"';
mysqli_query($link, $sql) or die(mysqli_error($link));
if (mysqli_affected_rows($link)) {
// Sponsor code hasn't been used before and is valid
}
}

Related

Q: PostGreSQL How to Pass POST information in a SQL command more efficiently

I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.

Complicated Database Setup: Trying to display two field values that correspond to three other specific fields

I am creating a page to display a bunch of information from a database, but the database that I am working with is set up funky.
While there are about 15 columns, the ones I am concerned with are:
Config_Name, Config_Type, Seq_Nbr, Question, and, Answer.
Each Config_Type has a different set of Seq_Nbr Values.
So I have a Config_Type called "_Hosting" which has about 12 different "Seq_Nbr" values. Each value corresponds to a different "Question" and "Answer" field. For example,
Examples:
When any given Config_Name, Config_Type = _Hosting & Seq_Nbr = 60; the Question field will be
"Control Panel URL" and the Answer field will be
"www.examplesite.com/cpanel"
When any given Config_Name, Config_Type = _Hosting & Seq_Nbr = 70; the Question field will be
"Control Panel Username" and the Answer field will be "someusername"
What I am trying to do is get all of the information displayed on one page.
I was thinking that I could use the code and query individual values for each section (from the examples):
<?php
$sql = "SELECT Question, Answer FROM configs WHERE Config_Name='Company', Config_Type = '_Hosting', Seq_Nbr = '60'";
$result = mysql_query($sql)or die(mysql_error());
$content = $result
?>
And then echo it into each individual field:
<p>
<h2><? echo "Control Panel URL"; ?><h2>
<br></br>
<h4><? echo $content; ?><h4>
</p></br>
But because I have to do this for 10+ "Seq_Nbr" values, this entire process seems tedious and unnecessarily repetitive. I know I could probably implement a switch() and have it go through different SQL queries, but I am trying to find a more efficient way to do this.
Any ideas would be greatly appreciated!
(I know the code isn't entirely correct, I am just trying to convey the method)
Thanks!
Why not just query all and display all??
And use an ORDER BY to organize it however you want....
//Google PDO to learn more, and how to connect
//Connect
$conn = new PDO("...");
$sql = "SELECT * FROM configs ORDER BY Seq_Nbr";
foreach($conn->query($sql) as $val){
echo "Name :". $val['Config_Name']."<br>";
echo "Type :".$val['Config_Type']."<br>";
echo "Question :". $val['Question']." | Answer :".$val['Answer']."<br>";
}
Forgive me if Im misunderstanding what you wanna do...
Also, Im using PDO in the example, just adapt what you need to if you're still gonna use mysql_*
if you want them all returned in one select, you might try an "in" clause.
$seq = "'60','70','80'";
$sql = "SELECT Question, Answer FROM configs WHERE Config_Name='Company' and Config_Type = '_Hosting' and Seq_Nbr in ( " . $seq . " ) ";

Append 2 Mysql rows

I have a two step registration, one with vital data, like email username and password, and a second optional one with personal info, like bio, eye color, etc.. i have 2 exec files for these, the first ofc writes the data in the first part of the database, leaving like 30 columns of personal data blank. The second one does another row, but with the vital data empty now.. I would like to append, or join these two rows, so all the info is in one row..
Here is the 2nd one
$qry = "UPDATE `performers` SET `Bemutatkozas` = '$bemuatkozas', `Feldob` = '$feldob', `Lehangol` = '$lehangol', `Szorzet` = '$szorzet', `Jatekszerek` = '$jatek', `Kukkolas` = '$kukkolas', `Flort` ='$flort', `Szeretek` = '$szeretek', `Utalok` = '$utalok', `Fantaziak` = '$fantaziak', `Titkosvagyak` = '$titkos_vagyak, `Suly` = '$suly', `Magassag` = '$magassag', `Szemszin` = '$szemszin', `Hajszin` = '$hajszin', `Hajhossz` = '$hajhossz', `Mellboseg` ='$mellboseg', `Orarend` = '$orarend', `Beallitottsag` = '$szexualis_beallitottsag', `Pozicio` = '$pozicio', `Dohanyzas` = '$cigi', `Testekszer` = '$pc', `Tetovalas` ='$tetko', `Szilikon` ='$szilikon', `Fetish1` = '$pisiszex', `Fetish2` = '$kakiszex', `Fetish3` = '$domina', `Testekszerhely` = '$pchely', `Tetovalashely` = '$tetkohely', `Csillagjegy` = '$csillagjegy', `Parral` = '$par', `Virag` = '$virag' WHERE `Username` ='" . $_POST['username']. "'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: perf_register_success.php");
exit();
I'm not sure if $_POST works here. I have the form, then the exec of that form, which works, then this form, and this is the exec of that.. Anyway I always get "query failed" message, which is in the else statement of the 'if' i'm using. What am i doing wrong?
Thanks!
The correct syntax for UPDATE is as follows:
UPDATE table SET columnA=valueA, columnB=valueB WHERE condition=value
(documentation here)
Thus, your query should look like the following:
$qry = "UPDATE performers SET Bemutatkozas = $bemuatkozas, Feldob = $feldob, Lehangol = $lehangol [...] WHERE Username ='" . $_POST['username']. "'
You'll have to replace [...] with all your values (that's gonna take some time) but hopefully you get the pattern.
Other than that there are a number of things you should improve/change in your code but I'll just point you to jeroen answer in this question since he pretty much covers it all.
You want UPDATE instead of INSERT for your second query.
Apart from that you really need to fix that sql injection error, preferably by switching to PDO or mysqli in combination with prepared statements. The mysql_* functions are deprecated.
And whatever solution you take, you need to add proper error handling, suppressing errors is wrong, especially when you try to fix a problem but even in a production site, errors need to be logged, not ignored.

Using PHP to add a field in MySQL if it doesn' texist

I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.

"insert into $schoolname ('cat','...) The $_POST " if statement " is not passing values into $schoolname table

I'm having problems getting $schoolname to read in the "insert into" mysqlcommand.
I'm just creating a small thing for a fan club that spans a few schools. So i created a different database table for each school. Each school has a unique id, and the table name corresponds to that. The code is below. Please help. Well, the problem area is the insert portion.
"insert into $schoolname ('cat','...)
For some reason $schoolname is not catching with the $_POST if statement
the mysql command " insert into .... " passes values if i specify a hard coded table name, but it does not pass values if i specify the variable ($schoolname) in place of the table name. I need to specify the variable because there a number of schools with each having their own tables.
<?php
require_once('include.php');
include('imageupload.php');
$schoolid='';
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
{
$schoolid .= 'and id ='.$_GET['schoolid'];
}
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
$school = $resschoolid[0];
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
if($_POST)
{
(isset($_POST['pr']) && $_POST['pr'] != "") ? $price=mysql_real_escape_string($_POST['pr']) : $pr="" ;
$sqlclass = "insert into $schoolname(`category`,`type`,`price`,`title`,`description`,`weburl`,`image`,`email`,`phone`,`address`,`city`,`state`,`zip`,`postdate`,`sponser`,`status`)
values('".$_POST['subcategory']."','".$_POST['type']."','".$pr."','".mysql_real_escape_string($_POST['title'])."','".mysql_real_escape_string($_POST['description'])."','".mysql_real_escape_string($_POST['weburl'])."','".$imagename."','".mysql_real_escape_string($_POST['email'])."','".mysql_real_escape_string($_POST['phone'])."','".mysql_real_escape_string($_POST['address'])."','".mysql_real_escape_string($_POST['city'])."','".mysql_real_escape_string($_POST['state'])."','".mysql_real_escape_string($_POST['zip'])."','".date('Y-m-d H:i:s')."','0','Active')";
}
?>
Since you haven't specified what problem you're seeing, this is only a guess:
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
Shouldn't that be
if(isset($_GET['schoolid']) && $_GET['schoolid'] != '')
As a side note, consider what happens if the user entered the following in schoolid:
0; delete from schools
This is known as SQL Injection, and you should be using "bind variables" instead of building the query by concatenating strings.
The problem seems to be the below query:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
What is $schoolid variable at the end? I see what is $schoolid variable and I assume that the variable isn't set correctly.
From what I understand is that the above query might be throwing an error and therefore $schoolname isn't populated at all. Can you please try to print how that query looks like?
EDIT 1 Reading the past discussions, it is clear that $schoolname variable is empty, i.e. has no value. It is not the scope issue because from your code $schoolname is in the global scope and is therefore available inside the $_POST IF check. So let us try to debug the code to analyse options:
Can you put an echo $sqlschoolid; just after where you have written the query? This will confirm that the query format is correct
Assuming that the query is good, let us now check if the query is returning the right data? I'm not sure what DB class are you using, so I can't say what does $obj->sql_query() returns? Perhaps the MySQL resultset. Anyways, can you put var_dump($resschoolid) right after where it is initialized? And another var_dump($school) below?
This is how I would like you to put the debug statements:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
echo $sqlschoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
var_dump($resschoolid);
$school = $resschoolid[0];
var_dump($school);
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
I hope the above will give more insight into the problem. Let me know if you've any questions.

Categories