foreach Data Not Updateing in database - php

In my local server this script works fine. When I upload this script on live it does not work properly.
It inserts only 126 rows of data into the database, but I need to upload at least 500 rows at a time.
<?php
include 'database-config.php';
foreach($_POST['classroll'] as $row=>$classroll)
{
$sclassroll = $classroll;
$mark = $_POST['mark'][$row];
$type = $_POST['rtype'];
$session = $_POST['rsession'];
$department = $_POST['rdepartment'];
$examtype = $_POST['rextype'];
$examyear = $_POST['rexyear'];
$examsubject = $_POST['rexmarksubject'];
$stmt = $dbh->prepare("INSERT INTO exammarks(studnettype, studentsession, studentdepartment, studentclassroll, examtype, examyear, examsubjec, exammarks) VALUES (:studnettype, :studentsession, :studentdepartment, :studentclassroll, :examtype, :examyear, :examsubjec, :exammarks)");
$stmt->bindParam('studnettype', $type);
$stmt->bindParam('studentsession', $session);
$stmt->bindParam('studentdepartment', $department);
$stmt->bindParam('studentclassroll', $sclassroll);
$stmt->bindParam('examtype', $examtype);
$stmt->bindParam('examyear', $examyear);
$stmt->bindParam('examsubjec', $examsubject);
$stmt->bindParam('exammarks', $mark);
$stmt->execute();
}
header('Location: ../home.php');
?>

It is possible that your exammarks table definition on your live server contains a unique index that is not present on your local host server. If that were true some of your INSERT operations might fail.
The code you showed us doesn't check for errors. Obviously, when your program deals with high value data (such as the results of student examinations) you should check for errors.
Try this instead:
if( !$stmt->execute()) {
print_r( $arr = $stmt->errorInfo() );
}
else {
/* INSERT statement completed correctly */
}

Related

Undefined Variable Error Thrown When Using A $_GET Request

I have a page that connects to a MySQL database via PHP. On this page the data is fetched to load an image and its related details. This page all work OK when the page is loaded.
I also have a module included on this page where users can create a board (which will hold images) along a certain theme.
On other pages this board module works OK, but on a page where a $_GET request happens, which is needed to identify a user's username or an image filename (depending on the page), the board module doesn't work correctly. When you create a new board it fails and I get a PHP error saying Undefined variable: filename in with reference to the line of code ':filename' => $filename in the execute function below.
When this boards module is used to create a new board name I have some JavaScript fetch() code on the page that prevents a hard refresh. I'm not sure if this is causing the problem (although this JS is also used on the pages that don't have a problem, i.e. no $_GET request). On pages where this is no $_GET request everything works as expected.
Note: in the code below $connection is the database connection from a db.php file
PHP on pageload that loads the image and related data
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
$image_stmt = $connection->prepare("SELECT * FROM `lj_imageposts` WHERE `filename` = :filename");
$image_stmt -> execute([
':filename' => $filename // variable that returns the error
]);
$image_row = $image_stmt->fetch();
// if the GET url parameter doesn't exist/changed
if ($image_row == 0) { header ("Location: index.php"); exit; }
$db_userid = htmlspecialchars($image_row['user_id']);
$db_image_id = htmlspecialchars($image_row['image_id']);
$db_image_title = htmlspecialchars($image_row['image_title']);
$db_image_filename = htmlspecialchars($image_row['filename']);
$db_image_ext = htmlspecialchars($image_row['file_extension']);
$db_username = htmlspecialchars($image_row['username']);
?>
---- HTML OUTPUT THAT INCORPORATES THE ABOVE VARIABLES
PHP for the boards module
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
if(strlen(trim($create_board_name)) < 10) {
$error[] = "Board name must be at least 10 characters long";
}
if(strlen(trim($create_board_name)) > 150) {
$error[] = "Board name can be at less than 150 characters long";
}
if(!isset($error)) {
try {
$createBoardSQL = "INSERT INTO lj_boards (board_name, user_id) VALUES (:board_name, :user_id )";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
} else {
// give values an empty string to avoid an error being thrown before form submission if empty
$create_board_name = "";
}
This first line is unnecessarily cryptic, making the mistake harder to spot (and harder to fix):
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
It's pretending to be an expression, but it's actually an if statement in disguise - it consists of nothing but side effects. Let's write it out more clearly:
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
}
Now we can look more clearly at what each branch does:
The if branch sets a variable. If the code takes that branch, everything should be fine.
The else branch sets a header to be included when PHP sends the response. It doesn't do anything else, and it doesn't set the variable, so if this path is taken, you'll have a problem later.
What you probably intended to happen was for the else branch to set that header and then immediately stop processing. For that you need an exit; statement (also known as die;
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
exit;
}

SQLite3::exec failed

Below is my code. $sqlite->exec cannot return true. I used echo to output the insert statement above this line of code. The statement is correct, and it can be inserted normally when executed directly on the command line. But using $sqlite->exec does not work.
static function addContent($ja, $tc, $sc, $comment) {
$ja = trim($ja);
$tc = trim($tc);
$sc = trim($sc);
$sqlite = new SQLite3('/home/bitnami/htdocs/converter');
if ($sqlite) {
$query = "insert into hanzi values (null, '$ja', '$tc', '$sc', '$comment')";
echo $query . '<br />';
$result = $sqlite->exec($query);
if ($result) {echo '$result is OK';} else {echo '$result os not OK';}
}
return $result;
}
There is no problem with the database connection, that is, the result of $sqlite = new SQLite3('/home/bitnami/htdocs/converter'); is correct, otherwise the echo below could not be executed.
This code was working fine on a Cent OS server before, and now I moved it to a LAMP environment in AWS Lightsail.
Other parts of the code that use the select statement $sqlite->query($query) can be executed.
I used .log to collect the log, but there is no record of execution failure in the log.

GD Library image generation does not work with mySQL query

Long story short, I have a project that requires creating a user's avatar based on their data from the database. The avatar is generated using the imagepng() and imagecopy() functions.
The user's avatar can either be male or female and that preference is saved in an SQL database as column "user_gender" where "0" = female and "1" = male:
Screenshot of table in phpmyadmin
So the idea is that we take the data from the database, assign the value (0 or 1) to a variable, then use that variable to generate the image. See code below:
<?php
//Database connection script not included, but works fine
$id = 1;
$sqlQuery = "SELECT * FROM table WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array(':id' => $id));
while($rs = $statement->fetch())
{
$gender = $rs['user_gender'];
}
if($gender == "0")
{
//Allocation of images, file paths
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/male/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This code however, does not work as it results in a blank black page on the browser.
HOWEVER, this code, without any pulling from the database, works perfectly fine:
<?php
//taking out the sql query and just creating a $gender variable for testing
$gender = "0";
if($gender === 0)
{
$bodytype ="images/female/f_body.png";
}
else
{
$bodytype ="images/female/f_body.png";
}
header('Content-Type: image/png');
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
imagepng($destination);
?>
This is the output with the second code, showing that the image generation is indeed functional and the problem is most likely the passing from sql to php:
Working image generation in browser
I'd be extremely grateful to know what I am doing wrong or being hinted as to why the code stops working if the variable is pulled from the database.
Thank you!
I tried your code and encountered the same problem so I did some digging it and found that nothing was returned from the database so what I did was prefix the database name along with the tablename and it worked. See code below
$gender = '';
$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));
while($rs = $statement->fetch())
{
$gender = $rs['gender'];
}
if($gender == 0)
{
$bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
$bodytype ="images/male/m_body.png";
}
$destination = imagecreatefrompng($bodytype);
imagealphablending($destination, true);
imagesavealpha($destination, true);
header('Content-Type: image/png');
imagepng($destination);
Try it and let me know how it goes.

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.

PHP update which does not update form fields which are blank

This is an extension of a question I asked a wee while ago which #eHussain was nice enough to help out with.
I have form which inserts various details into a MySQL table and uploads a file (the name of which is also registered in the database). This works fine. The issue comes when I update, say, the name and not the image. In this case the image name is over written as 'blank', and rightly so as that's the value in the file field.
The update code:
<?php
error_reporting(E_ALL^E_NOTICE);
define('INCLUDE_CHECK',true);
include "connect.php";
$target = "../uploads/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$url=$_POST['url'];
$description=$_POST['description'];
$pic=($_FILES['photo']['name']);
$author=$_POST['author'];
$company=$_POST['company'];
$published=$_POST['published'];
$dashboardID=$_POST['dashboardID'];
//Writes the information to the database
mysql_query("UPDATE dashboard SET name='$name', url='$url', description='$description', documentName='$pic', author='$author', company='$company', publish='$published' WHERE dashboardID='$dashboardID'");
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name'])) // check if any file is uploaded
{
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
header("Location: ../dashboard.php?success=2"); } else {
header("Location: ../dashboard.php?success=0"); }
}
?>
I understand the 'isset' to avoid a the error generated if no file is selected, but I don't understand how I can extent this to avoid updating a field which has a blank value.
Do a check on the $_FILES array before running the query.
From there, you can either dynamically build the query (including or excluding the documentName field) or alternatively, fetch the current value and assign it to $pic.
For example (untested)
$values = array(
'name' => $name,
'url' => $url,
// etc
);
if (isset($_FILES['photo']['name'])) {
$values['documentName'] = $_FILES['photo']['name']
}
// mysql functions are naff, use PDO
$query = 'UPDATE dashboard SET %s WHERE dashboardID = :dashboardID';
$set = array();
foreach (array_keys($values) as $col) {
$set[] = sprintf('`%s` = :%s', $col, $col);
}
$stmt = $pdo->prepare(sprintf($query, implode(', ', $set)));
$values['dashboardID'] = $dashboardID;
$stmt->execute($values);
#rrfive , please try below method, hope it will work,
//first put all post variable in an array
$post_data = compact($_POST);
$pic=($_FILES['photo']['name']);
//now push pic name in `$post_data`
if (!empty($pic) ) { array_push( $post_data,$pic ) }
//now use UPDATE query using `vsprintf` . but first check the order of `$post_data` #Thanks Phill
$stmt = "UPDATE dashboard SET
name='%s',
url='%s',
description='%s',
author='%s',
company='%s',
publish='%s'";
$stmt .=(!empty($pic)) ? documentName='%s', : "";
$stmt .= "WHERE dashboardID=%d";
// To check the complete query before execute. uncomment below 2 lines
//print vsprintf($stmt,$post_data);
//die;
mysql_query( vsprintf($stmt,$post_data) );
Reference
- compact
- vsprintf
The following code should do the trick.
if(isset($_FILES)){
...stuff...
}

Categories