Unable to get Table Name using variable string MYSQL Error - php

if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
$sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
$sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
$sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
$sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
$sectionTitle = "Theory Notes";
}
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
//very basic validation
if($contentTitle ==''){
$error[] = 'Please enter the Content Title !';
}
if($contentLink ==''){
$error[] = "Please enter the Content Link !";
}
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
$stmt->execute(array(
':contentTitle' => $contentTitle,
':contentLink' => $contentLink,
':contentAuthor' => $contentAuthor
));
//redirect to index page
header('Location: add-content.php?notallowed=true');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
}
}
Actually, problem started when I tried inserting Table name with variable. Tables exist in database. total 5 databases are there in which I will insert data according to users selection, but when form executed, a error is thrown saying:
SQLstate[42000]: SYNTAX ERROR OR ACCESS VIOLATION 1103, INCORRECT TABLE NAME ' '

The error INCORRECT TABLE NAME '' error means you don't have a value in $tableName. Your $_GET['category'] is not picking up a recognized value or the extract($_POST) is changing $tableName to an empty value.

I got the solution, I shifted tableVariables section inside try and its now working.

var dump your variable, post to see what value comes up.

Related

Cant insert Data into my Mysql Database?

I need a help from this error i cant insert data into my database, can you see my codes, im newly in php so please help me for this. thank you for your helping and giving a good answer,
it always saying "an error eccurred while sending" it is based on my else condition
<?php
if(isset($_SESSION['username']))
{
$form = true;
$orfvp_destination = '';
$oreq_approver= '';
$oreq_noter = '';
$orfvp_duration = '';
$orfvp_purpose = '';
//to check if the form has been sent
if(isset($_POST['rfvp_destination'], $_POST['req_approver'], $_POST['req_noter'], $_POST['rfvp_duration'], $_POST['rfvp_purpose']))
{
$orfvp_destination = $_POST['rfvp_destination'];
$oreq_approver = $_POST['req_approver'];
$oreq_noter = $_POST['req_noter'];
$orfvp_duration = $_POST['rfvp_duration'];
$orfvp_purpose = $_POST['rfvp_purpose'];
//to remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$orfvp_destination = stripslashes($orfvp_destination);
$oreq_approver = stripslashes($oreq_approver);
$oreq_noter = stripslashes($oreq_noter);
$orfvp_duration = stripslashes($orfvp_duration);
$orfvp_purpose = stripslashes($orfvp_purpose);
}
//to check if all the fields are filled
if($_POST['rfvp_destination']!='' and $_POST['req_approver']!='' and $_POST['req_noter']!='' and $_POST['rfvp_duration']!='' and $_POST['rfvp_purpose']!='')
{
//to protect the variables
$rfvp_destination = mysql_real_escape_string($orfvp_destination);
$req_approver = mysql_real_escape_string($oreq_approver);
$req_noter = mysql_real_escape_string($oreq_noter);
$rfvp_duration = mysql_real_escape_string(nl2br(htmlentities($orfvp_duration, ENT_QUOTES, 'UTF-8')));
$rfvp_purpose = mysql_real_escape_string($orfvp_purpose);
//to check if the recipient exists
$dn1 = mysql_fetch_array(mysql_query('select count(user_id) as req_approver, user_id as req_approverid, (select count(*) from request) as npm from users where user_username="'.$req_approver.'"'));
$dn2 = mysql_fetch_array(mysql_query('select count(user_id) as req_noter, user_id as req_noterid, (select count(*) from request) as npm from users where user_username="'.$req_noter.'"'));
if($dn1['req_approver'] and $dn2['req_noter']==1)
{
//to check if the recipient is not the actual user
if($dn1['req_approverid']!=$_SESSION['userid'] and $dn2['req_noter']!=$_SESSION['userid'])
{
$id = $dn1['npm']+1 and $dn2['npm']+1;
//We send the message
if(mysql_query('insert into rfv (rfv_id, rfv_code, rfv_driver, rfv_vehicle)values("'.$id.'", "RFV2015-'.$id.'", "", "")')
and mysql_query('insert into rfv-p (rfv_code, rfvp_destination, rfvp_purpose, rfvp_duration)values("RFV2015-'.$id.'", "rfvp_destination", "rfvp_purpose", "rfvp_duration")')
and mysql_query('insert into request (req_code, req_date, req_status, req_dateneeded, req_requestor, req_approver, req_noter, form_id)values( "RFV2015-'.$id.'", NOW(), "Waiting for Approval", "'.$_POST['req_dateneeded'].'", "'.$_SESSION['userid'].'", "'.$dn1['req_approverid'].'","'.$dn2['req_noterid'].'", 2)'))
{
?>
<p style="color:red" align="center" >Request Successfully Created!</p>
<p style="color:red" align="center" >Home</p>
<?php
$form = false;
}
else
{
//Otherwise, we say that an error occured
$error = 'An error occurred while sending the message';
}
}
else
{
//Otherwise, we say the user cannot send a message to himself
$error = 'You cannot send a message to yourself.';
}
}
else
{
//Otherwise, we say the recipient does not exists
$error = 'The recipient does not exists.';
}
}
else
{
//Otherwise, we say a field is empty
$error = 'A field is empty. Please fill of the fields.';
}
}
elseif(isset($_GET['req_approver'], $_GET['req_noter']))
{
//We get the username for the recipient if available
$oreq_approver = $_GET['req_approver'];
$oreq_noter = $_GET['req_noter'];
}
if($form)
{
//We display a message if necessary
if(isset($error))
{
echo '<div class="message" align="center" style="color:red">'.$error.'</div>';
}
//We display the form
?>
In the above script 2 if are not closed. First one is if(isset($_SESSION['username'])) and second one is if($form). Close the curly bracket } at correct place and that should work as expected.

PHP PDO not inserting or throwing error

The email is not being inserted into the database, however I am receiving an echo of success without any errors. I'm not sure what is going wrong. I've tried it with a duplicate email and I get the duplicate email message so it is connecting to the database, and it will not insert when it is a duplicate; however, it seems to not be inserting anything when it is not a duplicate. It seems to just skip the step of uploading.
<?php
include 'db_functions.php';
$_POST['email'] = 'somenewemail#gmail.com';
if(isset($_POST['email']) && ($_POST['email'] != NULL || $_POST['email'] != '')){
$ERRORS = array();
$cleanEmail = htmlentities($_POST['email']);
$database = dbconnlocal();
$queryEmailExists = $database->prepare("SELECT email FROM email_list WHERE email= ?");
$queryUploadEmail = $database->prepare("INSERT INTO email_list (email) VALUES ( ? )");
$database->beginTransaction();
try
{
$queryEmailExists->execute(array($cleanEmail));
$results = $queryEmailExists->fetchAll(PDO::FETCH_ASSOC);
$dbEmail = $results[0]['email'];
if(trim($dbEmail) == trim($cleanEmail)) {
// duplicate email
throw new Exception('duplicateEmail');
} else {
// new email
$queryUploadEmail->execute(array($cleanEmail));
echo json_encode('success');
}
}
catch (Exception $e)
{
switch(trim($e->getMessage())) {
case 'duplicateEmail':
// handle duplicate error
$ERRORS['error'] = 'duplicateEmail';
break;
default:
// handle default errors
$ERRORS['error'] = 'default';
break;
}
echo json_encode($ERRORS['error']);
}
} else { echo json_encode('emptyEmail'); /* empty email */ };
?>

A text form field needs to be required

I've been struggling to have a text form field required. So when some one doesn't fill his name he will receive an error like 'No title filled!'
I got this now but it doesn't work that well cause when I submit it insert into the db.
if(isset($_POST['submit'])) {
$update = "UPDATE post SET `title`='$_POST[title]', `pic`='$_POST[pic]', `youtube`='$_POST[youtube]' WHERE id = $_POST[id]";
$db->query($update) or die($db->error);
if($_POST['title'] == "") {
$error = "Title is required!";
}
if ($_POST['pic'] == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
echo '<p>Your post has been updated!</p>';
}
}
You need to stop your code from being executed if an error is found, not just echo the error. All your other code that submits the data to the database should ONLY be executed if there is no error. Try something like this:
Edit: Upon seeing the update to your code, this is what you need to do:
if(isset($_POST['submit'])) {
if(!isset($_POST['title']) || trim($_POST['title']) == "") {
$error = "Title is required!";
}
if (!isset($_POST['pic']) || trim($_POST['pic']) == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
$update = "UPDATE post SET `title`='" . mysql_real_escape_string($_POST['title']) . "', `pic`='" . mysql_real_escape_string($_POST['pic']) ."', `youtube`='" . mysql_real_escape_string($_POST['youtube']) ."' WHERE id = " . mysql_real_escape_string($_POST['id']);
$db->query($update) or die($db->error);
echo '<p>Your post has been updated!</p>';
}
}
The problem is, your data was being submitted to the database no matter what happened after with the validation - by the time you checked for errors it was too late, as the SQL had already been executed.
If you do it the way shown above, it will only submit if the $error variable is not set, which is what you want.
I wouldn't just rely on
if($_POST['title'] == "")
because it will not work if someone enters a space into the text field. For one thing, a title shouldn't be too long? So you can set a max-length for it?
Also maybe run a few more checks such as:
I wouldn't just rely on
if(!isset($_POST['title'] || $_POST['title'] == "" || $_POST['title'] == " ")
{
// Error
}
else
{
// Database query
}
You want the else, otherwise it will always execute the database query, whether or not they haven't filled out the form properly.

PHP Comparing variables returns false every time

I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}

Trying to get Unique entries set right for my form

so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>

Categories