My function doesn't post in the database - php

So I tried coding a function that allows the user to post a mood, chosen by a slider. I succeeded in connecting the color with an ID, then I tried making a post function. However Nothing happens.
this is where i call the functions.
if (isset($_POST['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}
these are the two functions.
public function getMood($moodColor){
$conn = db::getInstance();
$statementMood = $conn->prepare("SELECT * FROM moods WHERE color = :cMood");
$statementMood->bindParam(":cMood", $moodColor);
$statementMood->execute();
return $statementMood;
}
public function postMood(){
$conn = db::getInstance();
$statementPost = $conn->prepare("INSERT INTO postsmoodi (userID, moodID) VALUES (:userID, :moodID)");
$statementPost ->bindValue(':userID', $this->userID);
$statementPost->bindValue(':moodID', $this->moodID);
return $statementPost->execute();
}
this is the form where the button to post is.
<form class="input" action="mood.php" method="get">
<input id="hiddenValue" type="hidden" class="data" name="mood" value="">
<button class="moodReady" type="submit" name="ready">Ready</button>
</form>

Use $_GET instead of $_POST, as your form uses method="get"
if (isset($_GET['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}

Related

phpmyadmin not using DEFAULT value when input is left empty

I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">

Form does not go to action page on submit

Edit 2: I traced the code through the php, and realized that it was a faulty header that was causing it to bounce back. I've fixed the header and now the form behaves as it should. Thanks everyone for your help.
EDIT: I noticed the form is quickly refreshing when I submit, so I think it is going to the action page (createlist.php) and immediately bouncing back, so there must be some issue there. Here is the code for createlist.php:
<?php
if (!isset($_SESSION)) {
session_start();
}
if (!defined(__DIR__)) {
define(__DIR__, dirname(__FILE__));
}
require_once(__DIR__.'/../config.php');
//Connect to server and select database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Cannot connect to server');
//mysql_select_db(DB_DATABASE) or die('Cannot select database');
$tbl_name = 'lists'; //Table name
//Retreive data from form
$listname = $_POST['listName'];
$admin_id = $_SESSION['SESS_MEMBER_ID'];
$listtype = 'list';
//Create listname session variable for catinit.php
$_SESSION['listname'] = $listname;
//Insert new row
$sql = "INSERT INTO $tbl_name(admin_id, listname, listtype) VALUES ('$admin_id', '$listname', '$listtype')";
$result = mysqli_query($link, $sql);
if ($result) {
header("location: catinit.php");
} else {
die("Could not create list");
}
//mysql_close();
?>
I have 2 forms on a page, and while it was working before, since adding the backend handling of the information it has broken. Now when I submit either of the forms on the page nothing happens, it does not even attempt to load the action pages. I am completely lost as to what is stopping it from submitting, as everything looks like its working.
<h1>Create a New List</h1>
<form action = "createlist.php" method = "POST" id = "formId" onsubmit = "formValidate(0, 0, 0, 1, 'formId', 'submitError', event)">
<p>List Name:
<input type = "text" id = "listName" name = "listName" placeholder = "New List" onblur = "listNameValidate('listName','errorName1')" required><span class = "error" id = "errorName1"></span></p>
</form>
<h2>Categories</h2>
<ul class = "catList" id = "list">
<table>
<?php
$cats = array('Produce', 'Meat/Dairy', 'Baked Goods', 'Dry/Canned Goods', 'Household Items');
//Check to see if Session version of array has different values
if (isset($_SESSION['catArray']) && $_SESSION['catArray'] != $cats) {
$cats = $_SESSION['catArray'];
} else {
$_SESSION['catArray'] = $cats;
}
foreach ($cats as $cat) {
$index = array_search($cat, $cats);
echo '<tr><td><li>'.$cat.'</li></td><td> Remove</td></tr>';
}
?>
</table>
</ul>
New Category: <br>
<form action = "addcat.php" method = "POST" id = "addcat">
<input type = "text" id = "newCategory" name = "newCat" placeholder = "Category name" onblur = "listNameValidate('newCategory','errorName2')">
<input type = "hidden" name = "catArray" value = "<?php echo htmlentities(serialize($cats)); ?>" >
<input type = "submit" value= "Add" class = "add"><span class = "error" id = "errorName2"></span>
</form>
<h2>Invite Members</h2>
Add a new Member: <br>
<input type = "email" id = "email" name = "Email" placeholder = "Email Address" onblur = "emailValidate('email', 'errorEmail')">
<input type = "button" value = "Add" class = "add" ><span class = "error" id = "errorEmail"></span>
<p><input type = "submit" form = "formId" value = "Create"></p>
<p class = "submitError" id = "submitError"></p>

Mysql INSERT statement FAILING when POSTING large array

I've been searching the internet and "pulling my hair out" for days over this. It works fine on my XAMPP localhost and was working fine on my online testing server until I updated the PHP version and had to rewrite the code due to deprecated syntax.
Basically, I'm making a backend database for photography clients. One of the tables is designed to store image information. I haven't tried to store an actual image (BLOB of some sorts), I'm just looking to store "what and where".
What seems to be happening is if I try entering the contents of a shoot directory with several hundred images, when I hit input the screen changes, then instead of telling me how many were entered, it goes to a "418 unused" page saying
The server encountered an internal error or misconfiguration and was unable to complete your request.
I've been trying to narrow down which buffers to increase or variables like "max_allowed_packet", "max_input_vars"... still no luck. I've even tried comparing the phpinfo between the two servers to find out why one works and the other doesn't...
Here's what I'm doing... the listpage
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
$database = new Database();
$db = $database->getConnection();
$colname_chk_Images = "-1";
if (isset($_GET['ShootId'])) {
$colname_chk_Images = $_GET['ShootId'];
}
$colname1_chk_Images = "NULL";
if (isset($_GET['ShootFolder'])) {
$colname1_chk_Images = $_GET['ShootFolder'];
}
$colname_get_Images = "-1";
if (isset($_SESSION['cID'])) {
$colname_get_Images = $_SESSION['cID'];
}
$entered=0; //check for already entered images
?>
<?php
$dirname=$_SESSION['cIFolder'];
$Clogin=$_SESSION['Clogin'];
$ClientID=$_SESSION['cID'];
$_SESSION['CURR_CLIENT_ID'] = $ClientID;
$maindir=$_GET['ShootFolder'];
$ShootId=$_GET['ShootId'];
$dir=$_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF'])."protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$_SESSION['dir']=$dir;
$dir2="/protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$dirt= "/phpThumb-master/";
$dirn= dirname($_SERVER['PHP_SELF']);
$filesArray=array_map('basename', glob($dir."/*.jpg"));
$lightbox_data= "FPAD_Lightbox";
$thumb = "$dir2/";
$notThumb = "$dir2/";
$ic = count($filesArray);
$_SESSION['SESS_TOTNUM'] = $ic;
$_SESSION['sID'] = $ShootId;
$sID = $_SESSION['sID'];
include_once 'header_a.php';
?>
<div class="container">
<?php
echo $_SESSION['SESS_TOTNUM']." images found ";
echo "for Shoot ID#: ".$_SESSION['sID']."<br>";
echo "*Note* - if input boxes come up GREEN, then images are already loaded into the database";
?>
<p>
<?php
$images1 = new Image($db);
$images1->ShootId = $colname_chk_Images;
$images1->directory = $colname1_chk_Images;
$images1->ClientID = $colname_get_Images;
$chk_Images = $images1->checkImages();
$get_Images = $images1->getImages();
$Images = array();
while ($row_get_Images = $get_Images->fetch(PDO::FETCH_ASSOC))
{
$Images[] = $row_get_Images['image_name'];
}
?></p>
<form method="POST" name="form1" id="form1" action="input.php">
<table id="clientshoots" class="table table-condensed table-bordered table-small">
<tr>
<th>image_id</th>
<th>image_name</th>
<th>image_path</th>
<th>image_path_root</th>
<th>image_size</th>
<th>directory</th>
<th width="auto">ShootId</th>
<th width="auto">ClientID</th>
<th>ClientName</th>
<th>login</th>
</tr>
<?php $ic=0;
for($i=0;$i<count($filesArray);$i++) {
$fileinfo = $filesArray[$i];
$fname=$dir."/".$fileinfo;
$fname2=$dir2."/".$fileinfo;
$size = filesize($fname);
$atime = date("F d, Y H:i:s", fileatime($fname));
$mtime= date("F d, Y H:i:s", filemtime($fname));
$perms=decoct(fileperms($fname) & 0777);
$type=filetype($fname);
$pth=realpath($fname);
$name=basename($fname);
$dn=dirname($fname2);
if (in_array($fileinfo, $Images)) {
$entered=1;
echo "<style type=\"text/css\">\n";
echo "input {\n";
echo "background-color:#00FF33;\n";
echo "}\n";
echo "</style>";
}
?>
<tr>
<td> </td>
<td><input type="text" name="image_name[]" value="<?php echo $fileinfo; ?>" readonly/></td>
<td><input type="text" name="image_path[]" value="<?php echo $dir; ?>" readonly/></td>
<td><input type="text" name="image_path_root[]" value="<?php echo $dir2; ?>" readonly/></td>
<td><input type="number" name="image_size[]" value="<?php echo $size; ?>" readonly/></td>
<td><input type="text" name="directory[]" value="<?php echo $maindir; ?>" readonly/></td>
<td><input type="number" name="ShootId[]" value="<?php echo $ShootId; ?>" readonly/></td>
<td><input type="number" name="ClientID[]" value="<?php echo $ClientID; ?>" readonly/></td>
<td><input type="text" name="ClientName[]" value="<?php echo $_SESSION['cName']; ?>" readonly/></td>
<td><input type="text" name="login[]" value="<?php echo $Clogin; ?>" readonly/></td>
</tr>
<?php next($filesArray);
$ic=$ic+1;
}
$_SESSION['SESS_IC'] = $ic;?>
</table>
<?php if ($entered == 1){
echo "Return";
} else {
echo "<input class=\"btn-primary\" style=\"background-color:\" id=\"Insert records\" type=\"submit\" value=\"Insert records\">";
}?>
<input type="hidden" name="MM_insert" value="form1">
<input type="hidden" name="sID" value="<?php echo $sID; ?>">
</form>
</div>
<br>
<!-- /container -->
<?php include 'footer_b.php'; ?>
and then the input.php page...
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
include_once 'objects/ratings.php';
$database = new Database();
$db = $database->getConnection();
$sID = $_SESSION['sID'];
$ic = $_SESSION['SESS_IC'];
$ma = $_SESSION['SESS_CLIENT_MULTI'];
$gn = $_SESSION['SESS_CLIENT_GRPNO'];
$cID = $_SESSION['cID'];
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
$image1 = new Image($db);
$count = count($_POST['image_name']);
$fileinfo = clean($_POST['image_name']);
//Check for duplicates
if($fileinfo != '') {
for($i=0;$i<$count;$i++) {
$fileinfo = clean($_POST['image_name'][$i]);
//echo $fileinfo;
$image1->image_name = $fileinfo;
$result = $image1->check4Dup();
if($result) {
if(count($result) > 0) {
$errmsg_arr[] = 'Image already entered into Database';
$errflag = true;
}
$result = NULL;
}
else {
die($e->getMessage());
}
next($count);
}
}
$image1->ic = $ic;
$num = $image1->create();
$colname_newImages = "-1";
if (isset($sID)) {
$colname_newImages = $sID;
}
$image1->ShootId = $sID;
$newImages = $image1->countOneShoot();
$row_newImages = $newImages->fetch(PDO::FETCH_ASSOC);
$totalRows_newImages = $newImages->rowCount();
$ic2 = $totalRows_newImages;
$_SESSION['SESS_TOTNUM_ENT'] = $ic2;
header("Location: rs_images.php");
include_once 'header_a.php';
?>
<div class="container">
<?php
echo "Success! Number of images entered is ".$ic2; ?>
<br><br>
<p><input name="Verify" type="button" value="Verify Inputs" onclick="MM_goToURL('parent','rs_images.php');return document.MM_returnValue"/></p>
</div>
<?php include 'footer_b.php'; ?>
And the Class file...
<?php
class Image{
// database connection and table name
private $dbh;
private $table_name = "images";
// object properties
public $image_id;
public $image_name;
public $image_path;
public $image_path_root;
public $image_size;
public $directory;
public $ShootId;
public $ClientID;
public $ClientName;
public $login;
public $ic;
public function __construct($db){
$this->dbh = $db;
}
// Clean Function
function clean($str){
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
// test function
function test(){
$ic = $this->ic;
$i=1;
$j=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
$Clogin = $login."');";
$i=$i+1;
$j=$j+1;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$Clogin;
//$stmt = $this->dbh->prepare($qry1st.$sql_array);
//$stmt->execute();
echo $qry1st.$sql_array;
}
}
// create function
function create(){
$ic = $this->ic;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = array(); // This is where we'll queue up the rows
$queue_num = 50; // How many rows should be queued at once?
$i=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
if ($i==($_SESSION['SESS_TOTNUM'])) {
$login_term = $login."');";
}
else
{
$login_term = $login."')";
$i=$i+1;
}
$sql_array[] = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$login_term;
// Add a new entry to the queue
$c=0;
if (count($sql_array) >= $queue_num)
{ // Reached the queue limit
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array)); // Insert those that are queued up
$addImages->execute();
$sql_array = array(); // Erase the queue
}//End if
}//end foreach
if (count($sql_array) > 0) // There are rows left over
{
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array));
$addImages->execute();
}
}
function checkImages(){
$query_chk_Images = "SELECT images.image_name FROM images WHERE ShootId = ? AND directory = ?";
$chk_Images = $this->dbh->prepare ($query_chk_Images);
$chk_Images->bindValue(1, $this->ShootId);
$chk_Images->bindValue(2, $this->directory);
$chk_Images->execute();
return $chk_Images;
}
// create function
function getImages(){
$query_get_Images = "SELECT * FROM images WHERE ClientID = ? ORDER BY image_name ASC";
$get_Images = $this->dbh->prepare ($query_get_Images);
$get_Images->bindValue(1, $this->ClientID);
$get_Images->execute();
return $get_Images;
}
// create function
function getImageID(){
$query_rsImageID = "SELECT * FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$rsImageID = $this->dbh->prepare($query_rsImageID);
$rsImageID->bindValue(1, $this->ShootId);
$rsImageID->execute();
return $rsImageID;
}
// create function
function get_image_id(){
$q = "SELECT image_id FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$stmt = $this->dbh->prepare($q);
$stmt->bindValue(1, $this->ShootId);
$stmt->execute();
return $stmt;
}
// create function
function countOneShoot(){
$query_newImages = "SELECT * FROM images WHERE ShootId = ?";
$newImages = $this->dbh->prepare($query_newImages);
$newImages->bindValue(1, $this->ShootId);
$newImages->execute();
return $newImages;
}
// create function
function check4Dup(){
$qry = "SELECT * FROM `images` WHERE image_name = ?";
$result = $this->dbh->prepare($qry);
$result->bindValue(1, $this->image_name);
$result->execute();
return $result;
}
}
I've striped out all the extra stuff I've tried, like entering the info one record at a time, binding the Values with colon prefixed field names instead of the ?'s. I've tried different loops. I think it comes down to trying to push too much through one query... but then why does it work on XAMPP and why was it working fine with PHP 5.2?
I appreciate any light that can be shed on this. This is my first ever post with regards to PHP, MySQL or anything site related, I've been learning this stuff as I go and had it 90% completed and debugged and when I put it online to do some real testing with the actual directories and client folders that's when I found out that between PHP 5.4 and 5.2, there have been a number of changes and I found myself rewriting almost every line to move up to either MySQLi or PDO/OOP. After doing a lot searching around the internet I've opted for the OOP approach and still need to rewrite even more of the code above to clean things up a ton, but right now I'm troubleshooting the INSERT failure which I have not been able to solve on my own or with the help of all the forums, posts and blogs I've read to date.

filling in form fields from previous database entry - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

PHP Redirect Depending on users Column data in MySQL

I have created a login page with Facebook login API. And i have stored the users data (name, gender and etc) into MySQL database (except the column "gorg" in my table) when they are login.
Then, I'll redirect the users to "newgg.php" which is have two links "Giver" and
"Gatherer". So, users can choose either one of them.
My sample code:
<?php
session_start();
error_reporting(E_ALL);
include('src/sql_handler.php');
include('src/facebook_handler_core.php');
$new_fb = new facebook_handler_core;
$new_fb->run();
if (isset($_SESSION['gorg']) == "Gatherer") {
header('Location: map.php');
}
?>
My goal is to redirect them depending on the button they push for there FIRST time visiting the page, heres the button code
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Giver" value="Giver">
</form>
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Gatherer" value="Gatherer">
</form>
and now last but not least, IF they have already previously chosen their type of user it needs to just redirect them depending on what the 'gorg' column reads in the users table.
any ideas to why my codes not working properly?
just in case you need them, here are the sql_handlers
<?php
class MySQL_Con {
private $host = 'localhost',
$user = 'NUNURBSINESS',
$pass = 'ASKMEANDMAYBE',
$db = 'teknolog_fruitforest',
$_CON;
function MySQL_Con() {
$this->_CON = mysql_connect($this->host, $this->user, $this->pass);
if(!$this->_CON)
die(mysql_error());
else {
$select_db = mysql_select_db($this->db);
if(!$select_db)
die('Error Connecting To Database'.mysql_error());
}
}
function End_Con() {
mysql_close($this->_CON);
}
}
?>
and now the facebook_handler_core.php
<?php
class facebook_handler_core extends MySQL_Con {
public $session,$_INFO = array(),$U_INFO = array();
public function run() {
require('src/facebook.php');
$set_fb = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'CANTTELLYOU',
'cookie' => true));
$this->session = $set_fb->getUser();
if($this->session != 0) {
$this->_INFO = $set_fb->api('/me');
if(!empty($this->_INFO))
$this->fb_session_handler();
}
}
function fb_session_handler() {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND email = '" .mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
} else {
$photolink = 'http://graph.facebook.com/'.$this->session.'/picture?type=square';
$query = mysql_query("INSERT INTO users(oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square, gorg, gender)VALUES('".mysql_real_escape_string($this->session)."','facebook', '".mysql_real_escape_string($this->_INFO['name'])."', '".mysql_real_escape_string($this->_INFO['first_name'])."','".mysql_real_escape_string($this->_INFO['last_name'])."','".mysql_real_escape_string($this->_INFO['email'])."','".mysql_real_escape_string($photolink)."','null','".mysql_real_escape_string($this->_INFO['gender'])."')") or die(mysql_error());
$query = mysql_query("SELECT * FROM users WHERE email='".mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
}
$SQL_CON->End_Con();
$gorg = $this->U_INFO['gorg'];
if($gorg != null) {
$_SESSION['gorg'] = $gorg;
}
$_SESSION['email'] = $this->U_INFO['email'];
$_SESSION['image'] = $this->U_INFO['pic_square'];
$_SESSION['gender'] = $this->U_INFO['gender'];
if($gorg != null) {
if($gorg == 'Giver') {
//redirect to Giver
header('Location: picktreetype.php');
}
if($gorg == "Gatherer") {
//redirect to Gatherer
}
}
return true;
}
function update_user($param) {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
if($param == 'Giver')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='100' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
if($param == 'Gatherer')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='30' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
$SQL_CON->End_Con();
if(!$query)
return false;
else
return true;
}
}
?>
Thanks in advance, i just cant get enough out of this site when it comes to gaining help and proper guidance i really appreciate all the help anyone has ever given me in the past.
The problem is you're doing
isset($_SESSION['gorg']) == "Gatherer"
as isset() returns a boolean result which, using ==, will match any non-explicitly-false value. You would have had direct evidence of the problem if you would have used === (identity comparison operator).
So, in your case, "Gatherer" is evaluated as non-FALSE, aka TRUE.
Every time.
You shouldn't use this kind of comparison; instead try:
isset($_SESSION['gorg']) && $_SESSION['gorg'] == "Gatherer"
if you wish to keep checking whether gorg is set before doing any other evaluation.

Categories