SQL doesn't update when trying to pass array - php

I'm trying to input some values in event.php and store them in an array ($mem). I'm then passing this array in another eventregister.php file where I'm inserting it in MySQL table.
Starting lines in my event.php file:
<?php
session_start();
$slug = $_GET['slug'];
$sess_uid = $_SESSION['id'];
$sess_email = $_SESSION['email'];
$sess_name = $_SESSION['name'];
if(isset($_POST['submit'])&&$_POST['submit']=='register1')
require_once('13/functions/eventregister.php');
?>
In <body>:
...
...
$result = mysql_query("SELECT * FROM event WHERE slug = '".$slug."'");
if ($result == true){
$row=mysql_fetch_assoc($result);
$id=$row['id'];
}
$_SESSION['eventid']=$id;
$_SESSION['eventname']=$row['name'];
$_SESSION['max_members']=$row['members'];
php $mem=array_fill(0,$row['members'],'');?>
<form action="" method="post">
<?php for ($i=0;$i<$row['members']-1;$i++){
echo '<label>TRYST ID of Member '.($i+1).' :</label>';
echo '<input type="text" size="20" name="'.$mem[$i].'"><br>';
}
echo '<button type="submit" id="submit" value="Register" name="register1">Register</button>';?>
</form>
My eventregister.php file:
<?php
session_start();
foreach($_POST['mem'] as $key=>$value){
$value=mysql_real_escape_string($value);
if(strlen($value)==0)
$value="Null";
}
$sess_uid = $_SESSION['id'];
$sess_email = $_SESSION['email'];
$sess_name = $_SESSION['name'];
$e_id=$_SESSION['eventid'];
$e_name=$_SESSION['eventname'];
$e_max_mem=$_SESSION['max_members'];
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number) VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");
$url="events.php?slug=".$slug;
header('Location: ' . $url);
exit;
?>
The page doesn't show any error, redirects are working, its just that no rows get affected in SQL. I'm still in the learning process, hence using the old notations of PHP.

If you look closely at the INSERT statement, you see you have a stray comma at the end. Remove that:
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number)
VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");
You could also see the MySQL error in your server logs. Or call mysql_error to find out more if a query fails.
I also do not see a mysql_connect anywhere.

Your commas and brackets not organised
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number) VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

If statement doesn't execute even though condition is true

I'm at a complete loss here. I've written a relatively simple PHP script which updates a database record based on user input from a HTML form. The script contains an 'if' statement which executes based a hidden input. I know that the statement executes because the SQL query executes without a problem. The problem I'm having is that there there is another if statement within which should execute if the query object is set, but apparently it doesn't because the $message variable within is not assigned a value. I know that the query object is set because when I echo it it shows up as '1'. Below is the code block in question:
<?php
if(isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
The echoes and print_r() below the query are for debugging purposes. The code that should echo $message is above the aforementioned code block (in my script) and looks like this:
<?php if(isset($message)) {echo $message;} ?>
Also, I tried using isset() for the $r variable and also changed the condition to $r !== false but that did not make a difference. When I just echo out $message without the isset() i get the obvious " Undefined variable: message in C:\xampp\htdocs\IMS\modify.php on line 47" error. My apologies if I'm missing something glaringly obvious. I did search beforehand but all the answers were too different from my situation and my knowledge of PHP is too small for me to be able to connect dots that are that far away, if you know what I mean.
EDIT: alright, I might as well put in the entire script. It's a bit all over the place, my apologies. The $id and $table variables do show as undefined after the submit button is pressed, could that have something to do with it?
<?php
error_reporting(E_ALL);
include('config/setup.php');
$id = $_GET['id'];
$table = $_GET['table'];
if ($table == "users") {
header('Location: index.php');
exit;
}
?>
<html>
<head>
<title>Update</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="back">
Back
</div>
<div class="panel">
<?php
if(!isset($_POST['submitted'])) {
$q = "SELECT name FROM $table WHERE id = $id";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_assoc($r);
if($table == "categories"){
$type = "category";
} else if ($table == "products") {
$type = "product";
}
echo "<p>You are changing the properties of this ".$type.": ".$row['name']."</p>";
}
?>
<?php if(isset($message)) {echo $message;} ?>
<form action="modify.php" method="POST">
<label for="name">New name</label>
<input type="text" class="form-control" id="name" name="name">
<button type="submit">Submit</button>
<input type="hidden" name="submitted" value="1">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="table" value="<?php echo $table; ?>">
</form>
<?php
if(isset($_POST['submitted'])) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r !== false) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
</div>
</body>
EDIT2: Alright, I came up with a "fix" that kind of solves the problem, namely, I moved the if condition up before the echo of $message and changed the condition to isset($_POST['submitted']. This will have to do, I suppose. I guess I should read up more about the order of operations when processing submitted data and parsing PHP files in general, because I am quite confused as to why this "fix" even works...
This (conditional) statement is a false positive:
if(isset($_POST['submitted']) == 1)
What you need to do is either break them up into two separate statements:
if(isset($_POST['submitted']) && $_POST['submitted']== 1)
or just remove the ==1.
Your code is also open to a serious SQL injection. Updating a table and setting columns from user input is not safe at all.
At best, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, please note that you cannot bind a table and/or a column should you want to convert that to a prepared statement method.
Therefore the following will fail (when using a PDO prepared statement as an example):
$q = "UPDATE :table SET :name = :name WHERE id = :id;
or
$q = "UPDATE ? SET name = :name WHERE id = :id;
Read the following about this method, where that cannot be used:
Can I parameterize the table name in a prepared statement?
Can PHP PDO Statements accept the table or column name as parameter?

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

PHP: Delete || Confirm delete

I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..

Delete element from Mysql

using a drop-down list that's populated from database fields, i need to select an option and then delete that from the database. i'm trying to do this by sending the form to a process php page where i pull in the select option from the post array and then delete it from the database and return to the index page.
having issues with getting the array variable from the post array. can anyone help with some code on how to get the variable and then delete the mysql title
<form method="post" action="deleteReview_process.php">
<select name="title">
<?php
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?php } ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
---- and the process page ---
include 'inc/db.inc.php';
if($_POST['delete']) {
$title = $_POST['title'][$movieTitle]; <------ NOT WORKING
$sql = "DELETE" . $title . "FROM pageTitle";
mysql_query($sql, $conn)
or die("couldn't execute query");
header("Location: http://localhost/cms/index.php");
}
else
{
header("Location: http://localhost/cms/deleteReview.php");
}
Because your SELECT element is named "title," it will be represented as $_POST["title"] when it arrives to the backend script:
$title = $_POST['title'];
Also, your query needs to be corrected:
$sql = "DELETE" . $title . "FROM pageTitle";
Should be:
$sql = "DELETE FROM tableName WHERE title = '{$title}'";
$title is going to be in $_POST['title'] ie. $title = $_POST['title']

Categories