if statement on mysql query - php

i am trying to use the !isset on the '$class' variable to see if it has a value or not, and then base the mysql_query function on that. but it's a no go. see anything wrong?
<?php session_start();
$heyyou = $_SESSION['usern'];
$points = $_SESSION['points'];
$school = $_SESSION['school'];
$class = $_POST['class'];
$prof = $_POST['prof'];
$date = $_POST['dater'];
$fname = $_FILES['fileToUpload']["name"];
?>
<div id='contenttext' class='contenttext'>
<?php
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ('$heyyou', '$fname', '$date', '$prof', '$class')";
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query); }
mysql_close();
?>
<?php
if (($_FILES["fileToUpload"]["type"] == "image/gif" || $_FILES["fileToUpload"]["type"] == "image/jpeg" || $_FILES["fileToUpload"]["type"] == "image/png") && $_FILES["fileToUpload"]["size"] < 10000000)
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"upload/" . $_FILES["fileToUpload"]["name"]);
echo "Your file has successfully been uploaded, and is awaiting moderator approval for points." . "<html><br><a href='uploadfile.php'>Upload more.</a>";
}
else
{
echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb";
}
?>
</div>
</body>
</html>

Two major security problems with your code:
You're wide open to SQL injection attacks (see: http://bobby-tables.com/)
You're blindly trusting the user is not malicious for the file upload. The ['type'] and ['name'] fields are completely under user control, and it's trivial to hack the upload to say it's a gif while still uploading a PHP script. You then use the user-supplied filename, WHICH CAN CONTAIN PATH INFORMATION, and dump it directly to your server. This leaves the door wide open to a malicious user uploading any file they want, anywhere on the server.
Minor point #3:
You don't check if the database query succeeds. Never assume a query succeeds. Even if the SQL statement is perfectly valid, there's far too many other reasons that could make it fail anyways. Always check the query call with ... = mysql_query(...) or die(mysql_error()) as a bare minimum error handler.

Probably because $class is being set, by you. Try if (empty($class)){

I maybe wrong but class is a reserved word try another name and $class != ""
http://www.php.net/manual/en/reserved.keywords.php
BTW remove you DB Conect info please we me be nice but some of the people reading this may not be. ;-)

Try this, first initialize all your variables and then assign the POST values.
Eg:
$class='';
$class = $_POST['class'];
if (!isset($class)){
echo 'You need to pick a class for the content';
}

You can not use $class since class is a keyword reserved.
This may work too:
$query = "INSERT INTO uploadedfiles (usename, filename, date, teacher, class) VALUES ($heyyou, $fname, $date, $prof, $class)";
Since double quote can understand variables when they inside it.
Another think is date is a keyword too reserved by MySQL.
Finlly try to see what $_POST['class']; content like this:
echo $_POST['class'];
Because perhaps you forget to give a name to your html element.

The variable $class is always set because of $class = $_POST['class']. so isset($class) will always be true regardless of class posted value. notice the difference in below statements:
$class = '';
if (isset($class)) {
echo 'a';
}
if($class) {
echo 'b';
}
the output is: a
//replace this:
if (!isset($class)){
echo 'You need to pick a class for the content'; }
else{
mysql_query($query);
}
//with this:
if (isset($class) && $class){
mysql_query($query);
else{
echo 'You need to pick a class for the content'; }
}

Related

MySQLi update not working, mutilple colums and two where clauses

So I have been debugging this for over 30 minutes and I still can't figure out what I'm doing wrong. I just started using MySQLi and thats one of the things that I keep messing up. I think it might have something to do with preg_replace I have only used this once before so i still am not very good with it.
<?php
ob_start();
session_start();
include("../include/config.php");
include("../include/functions.php");
if (isset($_SESSION['pv1_session']) && $_SESSION['pv1_session'] == true) {
if (isset($_POST['submit'])) {
$uid = idinfo($_SESSION['pv1_user_id'],"idu");
$id = mysqli_real_escape_string($mysql, $_POST['fid']);
$post_name = mysqli_real_escape_string($mysql, $_POST['name']);
$post_tags = mysqli_real_escape_string($mysql, $_POST['tags']);
$name = preg_replace("/[^\w a-zA-Zа-яА-Я0-9._-]/u", "_", $post_name);
$tags = preg_replace("/[^\w a-zA-Zа-яА-Я0-9._-]/u", "_", $post_tags);
$file = preg_replace("/[^\wa-zA-Zа-яА-Я0-9._-]/u", "_", $post_name);
$update = mysqli_query($mysql,"UPDATE files SET name='$name', filename='$file', tags='$tags' WHERE user_id='$uid' AND filehash='$id'");
if (!$update) {
echo "<p>Unable to update file.</p>";
exit;
} else {
echo "<p>Success: Your uploaded file has been updated!</p>";
$pro_url = $web['url'].'/account/manage_uploads.php';
header("Location: $pro_url");
}
}
} else {
echo "ERROR: Please log in first!";
}
?>
Use "prepared statements" (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)
This gives you two advantages:
it handles the escaping for you (and also does it right: you do the escaping BEFORE the preg_replace, and that could go very wrong)
it also provides you with very easy debug. You put the parameters into an array, and you can simple echo out (print_r) the parameters array and see what your preg_replace has done.

why do the values are added to database when numbers are inserted in the student name?

this is my coding
i think there is something wrong in the validation part.
can plz anyone help me?
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("school", $con);
$student_fname=$_POST['student_fname'];
$student_lname=$_POST['student_lname'];
$student_ic=$_POST['student_ic'];
$student_age=$_POST['student_age'];
$student_race=$_POST['student_race'];
$student_gender=$_POST['student_gender'];
$student_phone=$_POST['student_phone'];
$student_class=$_POST['student_class'];
$student_email=$_POST['student_email'];
$student_add=$_POST['student_add'];
$student_city=$_POST['student_city'];
$student_state=$_POST['student_state'];
$student_postcode=$_POST['student_postcode'];
$student_id=$_POST['student_id'];
$student_pswd=$_POST['student_pswd'];
$student_cpswd=$_POST['student_cpswd'];
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false) {
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
}
if (ctype_alpha(str_replace(' ', '', $student_lname)) === false) {
echo "<script language='Javascript'>alert('Student Last Name must only contain letters!');
location.href='rstudent.php'</script>";
}
if (ctype_alpha(str_replace(' ', '', $student_city)) === false) {
echo "<script language='Javascript'>alert('City must only contain letters!');
location.href='rstudent.php'</script>";
}
if($student_pswd==$student_cpswd)
{
$sql="INSERT INTO student (student_fname, student_lname, student_ic, student_age,
student_race, student_gender, student_phone, student_class, student_email, student_add,
student_city, student_state, student_postcode, student_id, student_pswd, student_cpswd)
VALUES
('$_POST[student_fname]', '$_POST[student_lname]', '$_POST[student_ic]', '$_POST[student_age]',
'$_POST[student_race]', '$_POST[student_gender]', '$_POST[student_phone]',
'$_POST[student_class]', '$_POST[student_email]', '$_POST[student_add]', '$_POST[student_city]',
'$_POST[student_state]', '$_POST[student_postcode]', '$_POST[student_id]',
'$_POST[student_pswd]', '$_POST[student_cpswd]')";
}
else
{
echo "<script language='Javascript'>alert('Password must match!');
location.href='rstudent.php'</script>";
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<script language='Javascript'>alert('The Student Profile Has been Successfully
Registered!!!');
location.href='srecords.php'</script>";
mysql_close($con)
?>
why is my validation for only letters, when inserted numbers it still add in the database?
It's because the script continues it's normal execution when one of the validation statements fails.
Meaning, you are just echo-ing some javascript but this won't do anything to the normal php flow. The javascript will be outputed after php has done it's processing and inserted the values in the database.
In the IF statements you must take another action that will prevent the script in reaching the DB insert part.
Simplest solution for your case:
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false)
{
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
exit;
}
Notice the "exit" in the IF statement. This will cause the script to end execution when the validation fails, preventing the insert.
A better solution would be to have something like:
$form_validation = true;
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false)
{
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
$form_validation = false;
}
if($form_validation == false)
{
echo 'Form validation failed';
exit;
}
else
{
/* insert the values in the DB */
}
The solution above would allow you to check all statements before ending execution.
It would also be best to redirect using header('Location: rstudent.php'); exit; but this would require you to save the message in the $_SESSION and then check them.
So the best solution would be to save all error messages in an array, check the array if it's empty at the end of validation and if it's not save the error messages in the user $_SESSION, redirect the page using header('Location: rstudent.php''); exit; and in that page check for errors, display them to the user and clear them so that they won't show again :)
Nothing in this code remembers when a value was identified as invalid. You're generating some javascript, but not telling PHP to do anything else. Remember, by the time the javascript is rendered in the browser, the PHP server has already finished processing the PHP.
Create a variable such as $passes_validation=true;, Then everywhere you have a validation step, set $passes_validation=false; when the validation fails. Something like this:
$passes_validation=true;
if (ctype_alpha(str_replace(' ', '', $student_fname)) === false) {
echo "<script language='Javascript'>alert('Student First Name must only contain letters!');
location.href='rstudent.php'</script>";
$passes_validation=false;
}
Then, only execute the sql if $passes_validation==true. Something like this:
if($passes_validation){
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
}

If else block in PHP

I don't know where I am going wrong in else if logic...
I want to validate this signup script in 3 steps:
1st: check if any field is empty, in which case include errorreg.php and register.php.
2nd: If email already exists include register.php.
3rd: If all goes well insert data to the database.
<?php
$address =$_POST["add"];
$password =$_POST["pw"];
$firstname =$_POST["fname"];
$lastname =$_POST["lname"];
$email =$_POST["email"];
$contact =$_POST["cno"];
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q2=mysql_query("select * from customer where email='$email'");
$b=mysql_fetch_row($q2);
$em=$b[0];
if($password != $_POST['pwr'] || !$_POST['email'] || !$_POST["cno"] || !$_POST["fname"] || !$_POST["lname"] || !$_POST["add"])
{
include 'errorreg.php';
include 'register.php';
}
else if($em==$email)
{
echo 'email already present try another';
include 'register.php';
}
else
{
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q1=mysql_query("insert into customer values('$email','$password','$firstname','$lastname','$address',$contact)");
echo 'query completed';
$q2=mysql_query("select * from customer where email='$email'");
$a=mysql_fetch_row($q2);
print "<table border =2px solid red> <tr><th>id </th></tr>";
print "<td>$a[0]</td>";
print "</table>";
include 'sucessreg.php';
echo " <a href='newhome.php'>goto homepage</a>";
}
?>
There's a lot to correct here, but to your specific concern, that the "loop" doesn't go on to the second and third "steps", that's because you're thinking about this wrong. In an if/else if/else code block, only one of the blocks is executed at a time, the others are not. For instance, if a user submitted a number, we could tell them it was even or odd with the following:
if($_GET['number'] % 2 == 0){
echo "That's even!";
} else {
echo "That's odd!";
}
You are attempting to do one check, then another, then a third. In this case, you want to nest your conditionals (if statements) rather than have them come one after another, like so:
if(/* first, basic sanity check*/) {
if(/* second, more complex check */) {
if(/* final check */) {
// Database update
} else {
// Failed final check
}
} else {
// Failed second check
}
} else {
// Failed basic check
}
Some other comments on your code:
Pay attention to formatting - laying out your code in consistent and visually clear patterns will help make it easier to see when you make a mistake.
Use isset($_POST['variable']) before using $_POST['variable'], otherwise you'll get errors. One idea is to use lines like: $address = isset($_POST['address']) ? $_POST["add"] : ''; - if you don't know that notation, it lets you set $address to either the value from the $_POST array or '' if it's not set.
Use the variables you created, like $email and $contact, rather than re-calling the $_POST variables - they're clearer, shorter variable names.
Use the better MySQLi library, rather than the MySQL library.
Create one connection ($con = ...) to your database at the beginning of your script, and don't create a second one later on, like you do here.
Explicitly specify which connection your queries are running against - you say $q2=mysql_query("SELECT ...") but you should also pass the connection you've constructed,
$q2=mysql_query("SELECT ...",$con).
First of all you want to check if the property isset in your $_POST object:
if(isset($_POST["name"])
second you want to check if the value set is empty
if(isset($_POST["name"] && !empty($_POST["name"]))
now you just have to scale it up to check all your properties it would be handy to move it into a function like this
function ispostset($post_var)
{
if (isset($_POST[$post_var]))
{
if ($_POST[$post_var] != '')
{
return true;
}
else
return false;
}
else
return false;
}

PHP File exists not working?

I would like to check if a page exists. My file is article.php . The article's URLs are article.php?id=1 article.php?id=2 etc. But when I check it this way it doesn't work:
$filecheck = "article.php?id=$id";
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
But it always returns "Sorry this article does not exist."
How could I fix this?
Don't pass the query string to it.
$filecheck = 'article.php';
The file "article.php?id=$id" will not exist as it is not a physical file.
I am assuming that you are using the $id to find an article that exists in a database. If this is the case then the file_exists function is not what you need.
What you will need to do is write a quick MySQL statement to check if the article exists and then go from there.
Something like this perhaps:
$query = "SELECT * FROM articles WHERE id='$id'";
$result = mysql_query($query);
// Check if result is there (ie article exists)
if ($result) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
I hope that helps. Let me know if you need anything else.
It's because there is no file called: article.php?id=$id
There probably is a file called: article.php though :)
If they are physical page instead of dynamically created content use this way:
$filecheck = "article_1.php"
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}
Otherwise check the ID whether it is in the DB.
Well the reason it is not finding the file is because you have a querystring in it. If you are by chance getting this data from some other source and can't control if a querystring is sent with it then you can do this:
$yourFile = 'article.php?id=$id'; // Or wherever you get this value from
$yourFile = strstr( $yourFile , '?' , TRUE );
echo $yourFile; // now has a value of article.php

mysql insert success but nothing is added

look at this code
<?
require_once("conn.php");
require_once("includes.php");
require_once("access.php");
if(isset($_POST[s1]))
{
//manage files
if(!empty($_FILES[images]))
{
while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value))
{
$NewImageName = $t."_".$value;
copy($_FILES[images][tmp_name][$key], "images/".$NewImageName);
$MyImages[] = $NewImageName;
}
}
if(!empty($MyImages))
{
$ImageStr = implode("|", $MyImages);
}
}
$q1 = "insert into class_catalog set
MemberID = '$_SESSION[MemberID]',
CategoryID = '$_POST[CategoryID]',
Description = '$_POST[Description]',
images = '$ImageStr',
DatePosted = '$t',
DateExp = '$_SESSION[AccountExpDate]',
FeaturedStatus = '$_POST[sp]' ";
//echo $q1;
mysql_query($q1) or die(mysql_error());
}
//get the posted offers
$q1 = "select count(*) from class_catalog where MemberID = '$_SESSION[MemberID]' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);
header("location:AddAsset.php");
exit();
?>
The mySql insert function isn't adding anything also it return success to me , I've tried using INSERT ... Values but what it done was overwtiting existing value ( i.e make 1 entry and overwties it everytime).
I am using PHP 4.4.9 and MySql 4
I tried to add from Phpmyadmin and it is working also it was working after installation but after i quit the browser and made a new account to test it it is not working but the old ones is working ! you can see it here http://bemidjiclassifieds.com/
try to login with usr:openbook pass:mohamed24 and you can see it will be working but any new account won't work!
Maybe $_POST[s1] is not set or you are inserting into a different database than you are watching.
if(isset($_POST[s1]))
should probably be
if(isset($_POST['s1']))
(note the quotes). Also, it's best to NOT depend on a field being present in the submitted data to check if you're doing a POSt. the 100% reliable method is
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
As well, you're not checking if the file uploads succeeded. Each file should be checked like this:
foreach($_FILES['images']['name'] as $key => $name) {
if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
echo "File #$key failed to upload, error code {$_FILES['images']['error'][$key]}";
}
...
}
Don't use copy() to move uploaded files. There's a move_uploaded_files() function for that, which does some extra sanity checking to make sure nothing's tampered with the file between the time the upload finished and your script tries to move it.

Categories