Update a query by substracting a multiplicated number and using where - php

I'm making a paid to click website and I'm looking to update a query by substracting and a multiplicated number.
I'm trying to get the users to buy some ads package, they enter the views count and the cost per view, then when they click on "Submit", it should update the user in the current session. However, it's not working: it's updating all the users balances.
Here's my code :
<?php
session_start();
require_once '../constants/initSite.php';
$siteConstant->addFile('css', 'account.css');
echo $siteConstant->getHead();
echo $siteConstant->getMenu();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
require_once '../constants/class.DatabaseConstants.php';
require_once '../class/class.DBase.php';
$done = false;
$db = new DatabaseConstants();
$dBase = new DBase($db->getHost(), $db->getUser(), $db->getPass());
$dBase->setDatabaseName($db->getDb());
if(!$dBase->connectDatabase()){
die('SQL ERROR at db class vd fn');
}
$userQuery = mysqli_query($dBase->getDbobj(), "SELECT * FROM members WHERE username=\"".$_SESSION['username']."\"");
if(mysqli_num_rows($userQuery)){
$userData = mysqli_fetch_assoc($userQuery);
}else{
die('User Not Found!');
}
if(isset($_POST['submit'])){
$adquery = 'INSERT INTO ads (Title,Link,ViewLimit,Pays) VALUES ("'.$_POST['title'].'","'.$_POST['link'].'","'.$_POST['views'].'","'.$_POST['pays'].'")';
mysqli_query($dBase->getDbobj(), $adquery);
if(!mysqli_affected_rows($dBase->getDbobj())<1){
$done = true;
}
$id = 0;
$qryE = mysqli_query($dBase->getDbobj(), 'SELECT Id FROM ads');
while($dataE = mysqli_fetch_assoc($qryE)){
$id = $dataE['Id'];
}
$userQueryE = mysqli_query($dBase->getDbobj(),'SELECT id FROM members');
while($userDataE = mysqli_fetch_assoc($userQueryE)){
mysqli_query($dBase->getDbobj(), 'INSERT INTO view (MemberId,AdId) VALUES ("'.$userDataE['id'].'","'.$id.'")');
}
$userquery = ('UPDATE members SET balance=("'.$userData['balance'].'" - "'.$_POST['views'].'" * "'.$_POST['pays'].'") WHERE username="'.$_SESSION['username'].'"') ;
$userData = mysqli_fetch_assoc($userQuery);
}
?>
<center><img style="margin-bottom:5px"src="../image/ad468x60.png"/></center>
<div id="maincontent" style="height:35em">
<center>
<ul id="menu2">
<li>Account Details</li>
<li>Add Advertisement</li>
<li>Request Payment</li>
<li>Referrals</li>
<li>Account Setting</li>
</ul>
<br>
</center>
<center><p style="color:#0481b1;"><b><u>Add Advertisements</u></b></p></center>
<form id="msform" method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<center>
<?php
if(isset($_POST['submit']) && !$done){
echo '<h3 style="color:red;">Something went wrong!</h3>';
}
if ($done){
echo '<h3 style="color:green;">Advertisement Added and is Active.</h3>';
}
?>
<?php
if($userData['balance'] < 5 ){
echo '<h3 style="color:red;">insufficient balance</h3></br>
<h2 style="color:red;text-decoration:underline">You currently have '.$userData['balance'].' '.$siteData['currency'].' </h2>
<center><h2 style="color:red">You do not have enough balance to add an advertissement.<br><br>You need to have at least 5 '.$siteData['currency'].' in your account balance to add an advertissement.</h2></center>';
}
else {
echo'
Title <input type="text" name="title" placeholder="Enter Site Title" required="true"/> <br><br>
Link <input type="text" name="link" placeholder="Enter Site Link" required="true"/><br><br>
Number of Viewers to send<input type="text" name="views" min="100" placeholder="Enter number of views to send(100 Views Minimum)" required="true"/><br><br>
Reward per view<input type="text" name="pays" min="0.00001" placeholder="Enter reward per view(0.00001 '.$siteData['currency'].' Minimum)" required="true"/><br><br>
<input type="submit" name="submit" class="NormButton" Value="Submit" /> ' ;
}
?>
</center>
</form>
</div>
<?php
require_once '../main/footer.php';
$dBase->closeDatabse();
}else{
header('location: index.php');
}
echo $siteConstant->getTail();

Why is your where clause is before SET
Check this
"UPDATE members SET balance=($userData['balance'] - $_POST['views'] * $_POST['pays']) WHERE username=$_SESSION['username']"

Related

PHP and MySQL insert into multiple tables from one form

I am creating a simple site to keep records of users, customers, suppliers, etc.
I have created the forms to register clients and users using single forms capturing data through $ _POST form method
So far I have not had problems since the INSERTS are done on singles table which PK is an AutoIncremented field
In the code shown below, my goal is to let users create a vendor (name, phone number, email, address) as well as assign 1 or many vendor-category. This information is contained in one form
vendors, vendors-categories, users, etc. are stored in a MySQL database with the structure shown:
There is something wrong about my code after successfully create vendor and I am not sure how to solve the part that manages insertions in the join table (tblprovxrubro)
Code
<?php
session_start();
//available for admin, power-users and role-4
if ($_SESSION['rol'] ==2) {
header("location: ./");
}
include "../conexion.php";
if (!empty($_POST)) {
$alert='';
if (empty($_POST['razonSocial'])|| empty($_POST['email'])) {
$alert='<p class="msg_error">Vendor name and email must not be blank.</p>';
}else{
$razonSocial = $_POST['razonSocial'];
$email = $_POST['email'];
$domicilio = $_POST['domicilio'];
$telefono = $_POST['telefono'];
$usuario_id = $_SESSION['iduser'];
$query = mysqli_query($conection,"SELECT * FROM tblprov WHERE razonSocial = '$razonSocial'");
$result = mysqli_fetch_array($query);
if ($result >0)
{
$alert='<p class="msg_error">vendor already exists.</p>';
}else{
$query_insert = mysqli_query($conection, "INSERT INTO tblprov(razonSocial, numero, domicilio, email, idUsuario)
VALUES('$razonSocial','$telefono','$domicilio','$email', '$usuario_id')");
if ($query_insert)
{
$alert='<p class="msg_save">Vendor created succesfully.</p>';
//Once vendor is created I need his ID in order to insert in table
//tblprovxrubro as many records as vendor-types selected in form
//Not sure about how to achieve this
$queryBuscaprov = mysqli_query($conection, "SELECT id FROM tblprov WHERE razonSocial = '$razonSocial'");
$result_prov = mysqli_fetch_array($queryBuscaProv);
$idProv = $result_prov['id'];
foreach ($_POST['idRubro'] as $opcionSeleccionada)
{
//This INSERT should execute as many times as vendor-types selected in form
$query2 = mysqli_query($conection, "INSERT INTO tblprovxrubro (idRubro, idProv) VALUES ('$opcionSeleccionada', '$idProv')");
}
}else{
$alert='<p class="msg_error">Error creating vendor.</p>';
}
}
}
mysqli_close($conection);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include "includes/scripts.php"; ?>
<title>Registro de Proveedores</title>
</head>
<body>
<?php include "includes/header.php"; ?>
<section id="container">
<div class="form_register" name="form_register">
<h1><i class="fas fa-building"></i> Vendor List</h1>
<hr>
<form action="" method="post" class="form_register">
<div class="alert"><?php echo isset($alert) ? $alert : ''; ?></div>
<label for="razonSocial">Razón Social</label>
<input type="text" name="razonSocial" id="razonSocial" placeholder="Razón Social">
<label for="telefono">Número Telefónico</label>
<input type="text" name="telefono" id="telefono" placeholder="Número Telefónico">
<label for="domicilio">Domicilio</label>
<input type="text" name="domicilio" id="domicilio" placeholder="Domicilio">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="Email">
<?php
$query_rubro = mysqli_query($conection,"SELECT * FROM tblrubros");
mysqli_close($conection);
$result_rubro = mysqli_num_rows($query_rubro);
?>
<select name="rubro[]" id="rubro" multiple size="12">
<?php
if($result_rubro > 0)
{
while ($rubro = mysqli_fetch_array($query_rubro))
{
?>
<option value="<?php echo $rubro["idRubro"]; ?>"><?php echo $rubro["rubroDescripcion"] ?></option>
<?php
}
}
?>
</select>
<p>press Ctrl in order to select multiple options.</p>
<button name="submit" type="submit" class="btn_save"><i class="fas fa-save"></i> Crear Proveedor</button>
</form>
</div>
</section>
<?php include "includes/footer.php"; ?>
</body>
</html>
conection.php
<?php
$host = 'localhost';
$user = 'root';
$password = 'mypass';
$db = 'compras';
$conection = #mysqli_connect($host,$user,$password,$db);
mysqli_set_charset($conection,"utf8");
if(!$conection){
echo "connection error";
}
?>

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

Data not update when login is successfull in index.php?

I make a login page like user login. if registered then login with email and password(navigate register.php to index.php page) or sign up if not registered. works good but i want to add update functionality in my index.php page concept is simple if user wants to update its record then he make updations in a form and submit. I make a update query here but its shows Notice: Undefined index: id in C:\wamp\www\LOginKodingMadSimple\index.php on line 34. Where i am wrong ?
index.php :
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php
if (isset($_POST['UpdateUser']))
{
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = mysqli_real_escape_string($con, $_POST['id']);
//------- name can contain only alpha characters and space -------
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Name must contain only alphabets and space";
}
//------- Update users -------
if (!$error)
{
if(mysqli_query($con, "UPDATE users SET name='" . $name . "' WHERE id='" . $id . "'"))
{
$successmsg = "Successfully Updated! ";
}
else
{
$errormsg = "Error in Update...Please try again later!";
}
}
}
else
{
$errormsg = "Failed Please Try Again Later !";
}
?>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<?php if (isset($_SESSION['usr_id'])) { ?>
<li>
<p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p>
<a class="navbar-brand" href="updatephp.php">Update</a>
</li>
<li>
Log Out
</li>
<div style="border:1px dashed transparent;margin-top:400px;position:absolute;margin-left:-35%;">
<h1> Hello User <?php echo $_SESSION['usr_name']; ?> ! </h1>
<h1> Your Email is <?php echo $_SESSION['usr_email']; ?> ! </h1>
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type="submit" value="Update" name="UpdateUser">
</form>
</div>
<?php } else { ?>
<li>Login</li>
<li>Sign Up</li>
<?php } ?>
</ul>
</div>
add input hidden field with id like.
<input type="hidden" name="id" value="<?php echo $_SESSION['usr_id'];?>">
[NOTE: You don't have any textbox named as id.]
Choose any way.
Way 1)
Change
$id = mysqli_real_escape_string($con, $_POST['id']);
To
$id = $_SESSION['usr_id'];
Updated Code:
<?php
if (isset($_POST['UpdateUser'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = $_SESSION['usr_id'];
Way 2)
Add one hidden input field having value session usr_id.
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type='hidden' value="<?php echo $_SESSION['usr_id'];?>" name='id'>
<input type="submit" value="Update" name="UpdateUser">
</form>
In this way, your submitting form code will be same as you are having.
Use below function to hide the error notice :
error_reporting(0);

Changing Footer to label Login as Logout when the user is logged into the website

I need some help getting the login in my footer to change to logout if the user is logged in. I got it working on the login.php page, when the user logs in, it will label Log out, but if I go to About page, then it still says login. In my footer I have
<?php
if(isset($_SESSION['user'])) {
print("Log Out");
}
else{
print("Login");
}
?>
but it does not seem to work, only on the login page. I will post the code for the about,login, and footer pages below. I must be doing something amiss with sessions since its only working on the one page, but I cannot seem to find where. Sorry its a lot of code, but I wanted to paste it all just in case i didnt paste the part where the problem was occurring
Thank you so much
login.php
<?php
include "db.php";
if (isset($_POST['username']) && isset($_POST['password']))
{
$loginQuery = mysqli_query($con, "SELECT * FROM `users` WHERE `hashpassword` = '".sha1($_POST['password'])."' AND `username` = '".$_POST['username']."'");
if (mysqli_num_rows($loginQuery) == 1) $_SESSION['user'] = $_POST['username'];
}
?>
<?php
$pageName = "Administrator Login";
include 'header.php';
?>
<div class="one">
<?php
if(isset($_SESSION['user'])) {
echo "Welcome! You are logged in as : ".$_SESSION['user'];
//adding photos
print("<br/>Add A Photo");
$mysqli = new mysqli(DB_HOST,DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT DISTINCT photoYear FROM Photos");
print('<form method="post" enctype="multipart/form-data"><table>
<tr><td>*Upload Image</td><td><input type="file" name="newphoto"/></td></tr>
<tr><td>*Year To Upload To</td><td><input type="text" name="year"></td></tr><tr><td></td><td class="left"><input type="submit" name="sub" value="Add Photo" /></td></tr></table></form>');
}
else {
?><h1>Please Login Here To Make Administrative Changes</h1>
<form action="" method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Log In">
</form>
<?php } ?>
<?php
/* creating new year albums and uploading photos
if(isset($_SESSION['user'])){
//once user is logged in... can upload photos to certain years
/* Adding photo to year albums
print('<form method="post" enctype="multipart/form-data"><table>
<tr><td>*Upload Image</td><td class="left" ><input type="file" name="newphoto"/></td></tr>
<tr><td>*Year To Upload To</td><td class="left" ><select name="yearz">');
while($row = $result -> fetch_assoc()){
$year=$row[ 'photoYear'];
print("<option value=".$year.">".$year."</option>");
}
print('</select></td></tr><tr><td></td><td class="left"><input type="submit" name="sub" value="Add Photo" /></td></tr></table></form>');
if (!empty($_FILES[ 'newphoto' ]) && isset($_POST['yearz']) && isset($_POST['sub'])){
$newPhoto = $_FILES[ 'newphoto' ];
$year = $_POST['yearz'];
$errors= array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['newphoto']['size'] >= $maxsize) || ($_FILES["newphoto"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES['newphoto']['type'], $acceptable) && (!empty($_FILES['newphoto']['type']))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
//next
if(count($errors) ===0){
$originalName = str_replace(" ","_",$newPhoto[ 'name' ]);
$result = $mysqli->query("SELECT photoURL FROM Photos WHERE photoURL =".$originalName);
if (!($row = $result -> fetch_assoc())){
$test = explode('|', $_POST['alb']);
$albumid = $test[0];
$caption = $_POST[ 'caption' ];
if ($newPhoto['error'] == 0){
$tempName = $newPhoto[ 'tmp_name' ];
move_uploaded_file( $tempName, "$originalName");
$_SESSION[ 'photos'][] = $originalName;
print("File was uploaded.");
$adding = "INSERT INTO Photos (`photoURL`,`photoYear`)
VALUES('$originalName', '$yearz');";
$mysqli -> query($adding);
}
}
else{
print("This photo is already in the database. Try uploading another.");
}
}
else{
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die();
}
}
//outer
}
*/
?>
</div>
<?php
include "db.php";
include 'footer.php';
session_unset();
session_destroy();
?>
</html>
about.php
<?php
$pageName = "About RFYC";
include 'header.php';
?>
<div class="one">
<img class="center" src="images/logo/black.png" alt="logo">
<p>
Root For Your Cause is an annual charity root beer pong tournament held at Cornell University. The event is sponsored by Alpha Phi Omega - Gamma Chapter, a national community service fraternity. When registering for the event each team or organization selects a charity to play for. At the end of this single-elimination tournament, the entire sum of money earned through registration is then donated to the winning team's charity of choice!<br/>
</p>
<p>
The event is also friendly to spectators. There is music, plenty of chairs to watch friends compete, and we sell root beer floats throughout the competition.
The registration fee is $10 per two-person team for individual teams, and $8 per two-person team for organizations registering 5 or more teams who will all be competing for the same charity.
For more information, contact <span id="email">philanthropy#apogamma.org</span>
</p>
</div>
<div class="winners">
<h1>Past Winners</h1>
<figure>
<figcaption>2011<br/>
<img src="images/icons/placeholder_circle.png" alt="winner"><br/>
Team Name<br/>Charity</figcaption>
</figure>
<figure>
<figcaption>2012<br/>
<img src="images/icons/placeholder_circle.png" alt="winner">
<br/>Team Name<br/>Charity</figcaption>
</figure>
<figure>
<figcaption>2013<br/>
<img src="images/icons/placeholder_circle.png" alt="winner">
<br/>Team Name<br/>Charity</figcaption>
</figure>
</div>
<?php
include 'footer.php';
?>
</html>
footer.php
<div id="wrapper">
<div id="footer">
<div class="footerFloat">
<h4>Site Map</h4>
About <br/>
Rules<br/>
Gallery<br/>
Bracket<br/>
Register
</div>
<div class="footerFloat">
<h4>Connect With Us</h4>
<ul>
<li><img src="images/icons/email.png" alt="email"></li>
<li><img src="images/icons/fb.png" alt="fb"></li>
<li><img src="images/icons/twitter.png" alt="twitter" ></li>
</ul>
</div>
<div class="footerFloat">
<h4>Manage</h4>
<?php
if(isset($_SESSION['user'])) {
print("Log Out");
}
else{
print("Login");
}
?>
</div>
<div class="footerFloat">
<h4>Brought to You By</h4>
Alpha Phi Omega - Cornell Chapter
</div>
</div>
</div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/interactivity.js" type="text/javascript"></script>
session_start() needs to be included on all pages, or your session will not exist.

How to add action tag to form?

I have a working php guestbook script. It's only 1 file. I tried to validate it and there is only one error:
Line 147, Column 36: required attribute "action" not specified
<form method="post" name="blogform">
Now the code is this and I'm sure I would need to break up the file to two so that I can create a file for the action tag but I just don't know how. Any help is much appreciated.
<?php
session_start();
include("../../4a/inc/opendb.inc.php");
if(isset($_POST['send'])) //checks if $_POST variable "is set"
if(isset($_SESSION["ellenorzo"]) && !empty($_SESSION["ellenorzo"]) && $_SESSION["ellenorzo"]==$_POST["code"]){
$name = trim($_POST['name']); //eliminating whitespaces
$email = trim($_POST['email']);
$message = addslashes( trim($_POST['message']));
$query = "INSERT INTO blog (name, email, message, date) " .
"VALUES ('$name', '$email', '$message', NOW())";
mysql_query($query) or die('Hey, something is wrong!' . mysql_error());
header('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<?php
include('../../4a/inc/head.inc.php');
?>
<body style="color: #ffffff;">
<div class="mainblog">
<div class="top">
<div class="menu">
<?php
include('../menu.inc.php');
?>
</div>
</div>
<div class="middleblog">
<form method="post" name="blogform">
<input name="name" id="name" class="nameblog" type="text" />
<img src="../../4a/img/main/name.jpg" class="name" alt="Name" />
<input name="email" id="email" class="emailblog" type="text" />
<img src="../../4a/img/main/email.jpg" class="email" alt="Email" />
<textarea name="message" id="message" class="messageblog" rows="6" cols="6" onkeyup="return ismaxlength(this)">
</textarea>
<img src="../../4a/img/main/message.jpg" class="message" alt="Message" />
<input name="send" value="submit" id="send" class="sendblog" type="image" src="../../4a/img/main/send.jpg" onclick="return checkform();" />
<input type="hidden" name="send" value="submit" />
<div class="text_check_code">
<font class="text">
Enter the characters as they are shown below.
</font>
</div>
<img src="../../4a/inc/secure.inc.php" class="img_check_code" alt="Nospam" />
<input name="code" class="input_check_code" />
</form>
<?php
$rowsperpage = 10;
$pagenumber = 1;
if(isset($_GET['page']))
{
$pagenumber = $_GET['page'];
}
$offset = ($pagenumber - 1) * $rowsperpage;
$query = "SELECT id, name, email, message, date ".
"FROM blog ".
"ORDER BY id DESC ".
"LIMIT $offset, $rowsperpage";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
if(mysql_num_rows($result) == 0)
{
print("<br /><br /><br /><br /><br /><br /><br /><br />The blog is empty.");
}
else
{
while($row = mysql_fetch_array($result))
{
list($id, $name, $email, $message, $date) = $row;
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = htmlspecialchars($message);
$message = stripslashes(nl2br($message)); //real breaks as user hits enter
?>
<br />
<div class="blogentries">
<b><?=$name?></b>
<br />
<?=$message?>
<br />
<i><?=$date?></i>
</div>
<br />
<?php
} //closing while statement
$query = "SELECT COUNT(id) AS numrows FROM blog";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxpage = ceil($numrows/$rowsperpage); //rounding up any integer eg. 4,1=5
$nextlink = '';
if($maxpage > 1)
{
$self = $_SERVER['PHP_SELF'];
$nextlink = array();
for($page = 1; $page <= $maxpage; $page++)
{
$nextlink[] = "$page";
}
$nextlink = "Next: " . implode(' » ', $nextlink); //returns all elements of an array as a string
}
include ("../../4a/inc/closedb.inc.php");
?>
<br />
<div class="nextlink">
<?=$nextlink;?>
</div>
</div>
<br />
<br />
<div class="bottomblog">
<?php
require_once('../../4a/inc/copyright.inc.php');
?>
</div>
<br />
<br />
</div>
<?php //closing the else statement
}
?>
<?php
include('../../4a/inc/footer.inc.php');
?>
The action property specifies the link the form is sent to. If the form calls itself you can leave it blank:
<form action="" method="post" name="blogform">
The action tag tells the form where to submit the data. If it is left blank, it will attempt to submit the data to the current php page. If it's giving you trouble, perhaps you need to specify it and point it to the php page that generates the form.
In the code you provided, the bit of code which handles new inserts is at the top of this page, so you should set the action tag to be the name of the page.
By the way, you should ensure that your inputs are all cleaned; just using trim() before inserting them is asking for trouble. See here for more on this topic.

Categories