Accessing PHP array on separate script file? - php

I have this sample code but I am having trouble figuring out how to access the various array elements from a separate php script file called cart.php so that the fields from the code below are printed like a shopping cart before the user decides to confirm what they have selected with a continue checkout button.
<html lang="en">
<head>
<title>GreatBuy</title>
</head>
<body>
<?php
session_save_path('session');
session_start();
require_once 'login.php';
echo '<h1>GreatBuy</h1>';
//$_POST['username'] = 'abc1234';
//$_POST['password'] = '123456';
// get user's input
$username = $_POST['username'];
$password = $_POST['password'];
// check input
if (empty($username) || empty($password))
die('<p>Error: Username or password is empty/missing!</p>');
// connect to MySQL server to check user account
$conn = new mysqli($hn, $user, $passwd, $db);
if ($conn->connect_error)
die($conn->connect_error);
$hash = hash('ripemd128', $salt.$password);
$query = "SELECT * FROM greatbuy_users WHERE username = '$username' AND password = '$hash';";
$result = $conn->query($query);
if (!$result || $result->num_rows == 0)
die('<p>Error in username/password!</p>');
// get user's info and save it to session data
$user = $result->fetch_assoc();
$_SESSION['uid'] = $user['uid'];
echo '<p>User logged in!</p>';
$query = 'SELECT * FROM greatbuy_products ORDER BY cat, name;';
$results = $conn->query($query);
if ($results) {
$number_of_products = $results->num_rows;
echo '<form method="post" action="GreatBuy_cart.php">
<table border="1">';
echo ' <tr>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Manufacturer</th>
<th>Quantity Available</th>
<th>Quantity Selected</th>
<th>Select</th>
</tr>';
$n = $results->num_rows;
for ($i = 0; $i < $n; $i++) {
$product = $results->fetch_assoc();
echo ' <tr>
<input type="hidden" name="cart['.$product['pid'].'][pid]" value="'.$product['pid'].'">
<td>'.$product['name'].'</td>
<td>'.$product['cat'].'</td>
<td>'.$product['price'].'</td>
<td>'.$product['manufacturer'].'</td>
<td>'.$product['quantity'].'</td>
<td>
<input type="number" name="cart['.$product['pid'].'][userquantity]" '.(empty($product['quantity'])?'disabled':'').'>
</td>
<td>
<input type="checkbox" name="cart['.$product['pid'].'][checkout]" value="'.$product['pid'].'" '.(empty($product['quantity'])?'disabled':'').'>
</td>
</tr>';
}
echo ' </table>
<input type="submit" value="Review Order">
</form>';
}
?>
</body>
</html>

Related

Updating specific row on a table PHP

I have been trying to create a CRUD for a project and everything works great, except the update part. When I click the href of the edit of the specified row it does appear on the input fields. However when I click the editbtn the variables of the specific row are not updated and i am redirected where I was and the url gives me ?user=edited meaning that it went through the decision but for some reason they werent updated.
In my database there is one table(users) with the following rows user_id, user_uid, user_email, user_pwd, user_status and user_level. I am fairly new to php so i was hoping that you could pinpoint my mistake/s.
The connection to the database
dbh.inc.php
<?php
$dbServername = "localhost";
$dbUsername = "username";
$dbPassword = "*******";
$dbName = "username_Project";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName );
?>
The index
admin_panel_users.php
<?php
session_start();
include 'includes/dbh.inc.php';
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record= mysqli_query($conn, "SELECT * FROM users WHERE user_id=$id");
if ($record == 1 ) {
$n = mysqli_fetch_array($record);
$uid = $n['user_uid'];
$email = $n['user_email'];
$pwd = $n['user_pwd'];
$status = $n['user_status'];
$level = $n['user_level'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
.....
</head>
<body>
<?php
$result = mysqli_query($conn,"SELECT * FROM users");?>
<table border='2'>
<tr>
<th>Username</th>
<th>Email</th>
<th>Password</th>
<th>Status</th>
<th>Level</th>
<th>Actions</th>
</tr>
<?php while($row = mysqli_fetch_array($result)){?>
<tr>
<td><?php echo $row['user_uid'];?> </td>
<td><?php echo $row['user_email'];?></td>
<td><?php echo $row['user_pwd'];?></td>
<td><?php echo $row['user_status'];?></td>
<td><?php echo $row['user_level'];?></td>
<td>
<a href="admin_panel_users.php?edit=<?php echo $row['user_id']; >"
class="edit_btn">
<span class="glyphicon glyphicon-pencil"></span></a>
<a href="includes/deleteusers.inc.php?user_id=<?php echo $row['user_id'];>">
<span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
<?php } ?>
<tr>
<form class="something" action="includes/addusers.inc.php" method="POST">
<td><input type="text" name="uid" class="uid" placeholder="Username"
value="<?php echo $uid; ?>"></td>
<td><input type="text" name="email" class="email" placeholder="Email"
value="<?php echo $email; ?>"></td>
<td><input type="text" name="pwd" class="pwd" placeholder="Password"
value="<?php echo $pwd; ?>"></td>
<td><input type="text" name="status" class="status" placeholder="Status"
value="<?php echo $status; ?>"></td>
<td><input type="text" name="level" class="level" placeholder="Level"
value="<?php echo $level; ?>"></td>
<td>
<?php if ($update == true): ?>
<button type="submit" name="update" class="updatebtn">
<span class="glyphicon-pencil"></span> </button>
<?php else: ?>
<button type="submit" name="submit8" class="addbtnuser">
<span class ="glyphicon-plus"></span> </button>
<?php endif ?>
</td>
</form>
</tr>";
</table>";
<?php mysqli_close($conn); ?>
</body>
</html>
The functions
addusers.inc.php
<?php
include 'dbh.inc.php';
$uid = "";
$email = "";
$pwd = "";
$status = "";
$level = "";
$id = 0;
$update = false;
if (isset($_POST['submit8'])){
//INSERTS INTO
......
}
if (isset($_POST['update'])) {
$uid = mysqli_real_escape_string( $conn , $_POST['uid']);
$email = mysqli_real_escape_string( $conn , $_POST['email']);
$pwd = mysqli_real_escape_string( $conn , $_POST['pwd']);
$status = mysqli_real_escape_string( $conn , $_POST['status']);
$level = mysqli_real_escape_string( $conn , $_POST['level']);
$sql = "UPDATE users SET user_uid='$uid', user_email='$email',
user_pwd='$pwd', user_status='$status', user_level='$level' WHERE
user_id=$id";
mysqli_query($conn, $sql);
header ("Location: ../admin_panel_users.php?user=edited");
exit();
}
else{
header("Location: ../admin_panel_users.php");
exit();
}
From your addusers.inc.php, on the line that says:
$sql = "UPDATE users SET user_uid='$uid', user_email='$email',
user_pwd='$pwd', user_status='$status', user_level='$level' WHERE
user_id=$id";
It appears you didnt get the $id variable so as to update that particular row in your table. You defaulted it to 0 on line 8 of addusers.inc.php. So, it wont update any row at all because table rows start from 1 and increments.
On line 8, change it to
$id = $_GET['edit'] since you already passed it as a GET parameter here:
<a href="admin_panel_users.php?edit=<?php echo $row['user_id']; >"
class="edit_btn">
Your SQL text includes this:
WHERE user_id = $id
And $id is set to 0, so that's equivalent to
WHERE user_id = 0

PHP form input value doesn't work

I like to have a standard value filled in the input field.
I have this code:
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = '".$_GET['gebruiker']."' ");
$stma->execute();
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
/// my form
echo '<form method="POST" >
<table>
<th colspan="3"><h1>Gebruiker bewerken</h1></th>
<tr>
<th>
<h3>Gebruikersnaam: </h3>
</th>
<td>
<input style="width: 70%;" type="text" READONLY value="'.$Username.'" >
// the value must be filled in this input field
</td>
</tr>
<tr>
<th>
<h3>Wachtwoord: </h3>
</th>
<td>
<input style="width: 70%;" type="password" name="wachtwoord" REQUIRED>
</td>
</tr>
<tr>
<th>
</th>
<td colspan="2">
<input type="submit" name="bewerken" class="button" style="vertical-align:middle" value="Opslaan">
</td>
</tr>
'.$error.'
</table>
</form>';
The code doesn't fill in the value i got from the database.
I still get an empty form field.
My query returns 1 result row (i checked)
Does someone see my mistake?
I don't see the mistake i've made (it must me my mistake, it worked for me on other forms too)
To make sure it outputs all errors and warnings (for debugging), this might help:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Place above mentioned code at the top of your file.
And you might want to prevent any SQL injection as well:
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = ? ");
$stma->bindParam(1, $_GET['gebruiker'], PDO::PARAM_INT);
$stma->execute();
$stma->debugDumpParams(); // you could use this to check whether or not all parameters are set correctly
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
Below is a working example.
PHP
try {
$conn = new PDO('mysql:host=localhost;dbname=YourDBname', 'root', '');
} catch (PDOException $e) {
echo $e->getMessage();
}
$id = $_GET['gebruiker'];
$sql = "SELECT * FROM `users` WHERE id = :id";
$stm = $conn->prepare($sql);
$stm->execute(['id'=>$id]);
$user = $stm->fetchObject();
$username = $user->username;
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<form action="POST">
<input type="text" value="<?php echo (isset($username)) ? $username : 'No value' ; ?>">
</form>
</body>
</html>
If your set gebruiker from your url, then you just have do it like: script.php?gebruiker = 1 You can replace 1 with any ID value that exists in your table.
please try this code
$stma = $conn->prepare("SELECT * FROM `users` WHERE ID = '".$_GET['gebruiker']."' ");
$stma->execute();
$row_count = $stma->rowCount(); // returns 1
foreach ($conn->query($stma) as $rows) {
$Username = $rows['Username'];
}
**please replace this code**
$res = $conn->query("SELECT * FROM users WHERE ID = '".$_GET['gebruiker']."' ");
$allRows = $res->fetch_assoc();
$Username = $allRows['UserName'];

How do I update a specific row in a table using php form?

Please bear with me, I'm not familiar yet with the language. I have a table that lists an applicant record such as applicant number, name and status. I want to update an applicant status either 'hired' or 'failed' on a specific row using a PHP form. However, I'm not sure how to get the specific submit name on its row upon submission. Or if you have a workaround I would appreciate that. Thank you so much for your help.
<!DOCTYPE html>
<html>
<h2>Applicant Records</h2>
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password ="";
$mysql_database = "applicantrecord";
// Create connection
$conn = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqli = "SELECT id, firstname, lastname, status FROM applicant";
$result = $conn->query($sqli);
if ($result->num_rows > 0) { ?>
<table class="table">
<thead>
<tr>
<th>Applicant No.</th>
<th>Lastname</th>
<th>Firstname</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<?php
// output data of each row
echo "<tbody>";
while($row = $result->fetch_assoc())
{ ?>
<tr>
<td>
<?php echo $row["id"];
$appid = $row["id"];
?>
</td>
<td>
<?php echo $row["lastname"]; ?>
</td>
<td>
<?php echo $row["firstname"]; ?>
</td>
<td>
<?php echo $row["status"]; ?>
</td>
<td>
</td>
<td>
<div>
<form action="" role="form" method="post" name="form<?php echo $appid; ?>">
<select name="applicant_status">
<option value="Hired">Hire</option>
<option value="Failed">Fail</option>
</select>
</p>
<button type="submit" class="btn btn-default" name = "submit<?php echo $appid; ?>" data-dismiss="modal">Submit</button>
</form>
<?php
if(isset($_POST["submit"])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$newappid = $appid;
$newapptstatus = $_POST['applicant_status'];
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $connect ) {
die('Could not connect: ' . mysql_error());
}
$sql_sub = "UPDATE applicant ". "SET status = '$newappstatus'".
"WHERE id = '$newappid'" ;
mysql_select_db('applicantrecord');
$retval = mysql_query( $sql_sub, $connect );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
echo "<script type= 'text/javascript'>alert('An error occured! Applicant status update failed!');</script>";
}
echo "<script type= 'text/javascript'>alert('Applicant status updated successfully!');</script>";
mysql_close($connect);
}
?>
</div>
</td>
</tr>
<?php }
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</html>
In your if statement where you check that $_POST['submit'] is set, the index 'submit' does not exist. Thus isset($_POST['submit']) evaluates to false and your query to update the table is never being executed.
The variable $appid is being changed with each row that is added, so when the page is done loading and the submit button is pushed on a certain row, $appid won't necessarily contain the correct row number.
To get around this, you could use a hidden input in your form:
<input name="id" value="<?php echo $appid ?>" type="hidden">
Then you can replace isset($_POST['submit']) with isset($_POST['id']) and set $newappid = $_POST['id'] to get the row number to be changed.

No results during a search through Mysqli

I'm having the problem to pull out data from my database through a search field. I'm trying to protect my searchfield against Sql injection at the same time. Adding data to my database is working fine, and I think i did fine safetywise. Yet, pulling the data out seems to be harder.
All i'm trying to achieve is getting all the data from the person. I'm looking for "Bart" in my search field, so show me all the data from all the Barts in my database.
This is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:200' rel='stylesheet' type='text/css'>
<script src="script.js"></script>
</head>
<body>
<table class="table_form">
<form method="POST" action="test.php">
<tr>
<td>Voornaam: </td><td><input type="text" name="Voornaam"></td>
</tr>
<tr>
<td>Achternaam: </td><td><input type="text" name="Achternaam"></td>
</tr>
<tr>
<td>Adres: </td><td><input type="text" name="Adres"></td>
</tr>
<tr>
<td>Discipline: </td><td><input type="text" name="Discipline"></td>
</tr>
<tr>
<td>Graad: </td><td><input type="text" name="Graad"></td>
</tr>
<tr>
<td>Voeg toe aan databank: </td><td><input type="submit" name="Adddb" value="Bevestigen"></td>
</tr>
</form>
</table>
<table class="table_form">
<form method="POST" action="test.php">
<tr>
<td>Zoeken</td><td><input type="text" name="Voornaam" /></td>
</tr>
<tr>
<td>Bevestigen</td><td><input type="submit" name="zoeken" /></td>
</tr>
</form>
</table>
<div class="field">
<?php
require_once 'isset.php';
?>
</div>
</body>
</html>
This is the PHP
<?php
require_once 'login.php';
$db_con= new mysqli($db_host, $db_username, $db_password, $db_database);
$db_con->set_charset("utf8");
if($db_con->connect_error) die ("(" . $db_con->connect_error . " Error during connection");
if(isset($_POST['Adddb'])){
$stmt = $db_con->prepare("INSERT INTO customers (Voornaam, Achternaam, Adres, Actief, Discipline, graad) VALUES(?,?,?,NOW(),?,?)");
$stmt->bind_param("sssii",$voornaam, $achternaam, $adres, $discipline,$graad);
$voornaam = $_POST['Voornaam'];
$achternaam = $_POST['Achternaam'];
$adres = $_POST['Adres'];
$discipline = $_POST['Discipline'];
$graad = $_POST['Graad'];
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$db_con->close();
}
if(isset($_POST['zoeken'])){
$stmte = $db_con->prepare="SELECT * FROM customers WHERE Voornaam = (?)";
$stmte->bind_param("s", $zoeknaam);
$zoeknaam = $_POST['Voornaam'];
$stmte->execute();
echo $zoeknaam;
}
?>
Am i wrong to think that i'm not fetching something? And that is the reason i'm not getting anything?
EDIT ------>
Edited version as suggested below: Errors are gone but no results show up:
<?php
require_once 'login.php';
$db_con= new mysqli($db_host, $db_username, $db_password, $db_database);
$db_con->set_charset("utf8");
if($db_con->connect_error) die ("(" . $db_con->connect_error . " Error during connection");
if(isset($_POST['zoeken'])){
$zoeknaam = $_POST['Zoek']; // declare the input here
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam); // then use inside here
$stmte->execute();
$rows = $stmte->num_rows;
for($i=0; $i < $rows; $i++){
$row=mysqli_fetch_array($stmte, MYSQLI_ASSOC);
echo $row['Voornaam'] . '<br/>';
}
/*if($stmte->num_rows > 0) {
$results = $stmte->get_result();
while($row = $results->fetch_assoc()) {
echo $row['Achternaam'] . '<br/>';
// and other columns
}*/
}
?>
You should fetch the results properly by using ->get_result(). After that, you would be able to use ->fetch_assoc(). Example:
$zoeknaam = $_POST['Voornaam']; // declare the input here
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam); // then use inside here
$stmte->execute();
if($stmte->num_rows > 0) {
$results = $stmte->get_result();
while($row = $results->fetch_assoc()) {
echo $row['Voornaam'] . '<br/>';
echo $row['Achternaam'] . '<br/>';
// and other columns
}
}
If unfortunately, you do not have mysqlnd in your environment (if ->get_result() turns out the be Call to undefined method). Here's another way:
$zoeknaam = $_POST['Voornaam'];
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam);
$stmte->execute();
// get all columns
$meta = $stmte->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($stmte, 'bind_result'), $params);
while ($stmte->fetch()) {
echo $row['Voornaam'] . '<br/>';
echo $row['Achternaam'] . '<br/>';
}

Session user not changing

I've managed to reflect the user who logged in into a form. However now when a new user logs in, the previous user personal particulars eg name is still reflecting on the form. This is what i have so far. What am i missing out?
$result2 = mysqli_query($con, "SELECT admin_no FROM student_details;");
$row2 = mysqli_fetch_assoc($result2);
?>
<p>
<table border="1">
<tr>
<td width="410" align="center">Student Personal Data</td>
</tr>
<tr>
</td>
</tr>
<tr>
<td>Admission Number</td>
<td><input name= "name" type="text" disabled="disabled" value="<?php echo $row2['admin_no'] ?>"
size="40" readonly>
</td>
</tr>
This is how i my logout page looks like :
<?php
session_start();
session_unset();
session_destroy();
header('Location:login.php');
?>
My login page :
<?
$adminName = $_POST['txtName'];
$adminPassword = $_POST['txtPassword'];
$conn = dbConnect();
if (!$conn)
die("Couldn't connect to MySQL");
$query = "select * from ohrm_user where user_name='$adminName' and user_password= '$adminPassword'";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
if(mysql_num_rows($result) > 0 && $row['user_role_id'] == 1)
{
echo $_SESSION['user_name'] = $adminName;
echo $_SESSION['user_password'] = $adminPassword;
}
dbDisconnect($conn);
Insert session_start()
in first line of login and other control panel pages
look at this link
http://www.w3schools.com/php/php_sessions.asp

Categories