I'm working on an e-commerce project, currently on back end on the project where you can add or remove menus or sub-menues of categories .
I have checked dlls are enabled
That's the error I'm getting
Fatal error: Call to undefined function sanitize() in C:\xampp\htdocs\project\admin\categories.php on line 15
Here is the code
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/project/core/init.php';
include 'includes/head.php';
include 'includes/navigation.php';
$sql = "SELECT * FROM categories WHERE parent = 0";
$result = $db->query($sql);
$errors = array();
// when the form is cick process
$Category = '';
$parent= '';
if(isset($_POST) && !empty($_POST)){
$parent = sanitize($_POST['parent']);
$category = sanitize($_POST['category']);
$sqlform = "SELECT * FROM categories WHERE category ='$category' AND parent = '$parent'";
$fresult = $db->query($sqlform);
$count = mysqli_num_rows($fresult);
//if category is blank
if($category == ''){
$errors[] .= 'The category cannot be left blank';
}
//if it already exixt in database
if($count > 0){
$errors[] .= $category.' Already exits please choose a new category';
}
//display error or update database
if(!empty($errors)){
$display = display_errors($errors);?>
<script>
jQuery('document').ready(function(){
jQuery ('#errors').html('<?php $display;?>');
});
</script>
<?php } else{
//update database
$updatesql = "INSERT INTO categories(category,parent)VALUES ('$category','$parent')";
$db->query($updatesql);
header('location:categories.php');
}
}
?>
It seems to me that, sanitize isn't defined in scope. It's not a standard function so it should be somewhere within your code. You can most likely substitute it directly with mysqli_real_escape_string like this:
$parent = mysqli_real_escape_string($_POST['parent']);
$category = mysqli_real_escape_string($_POST['category']);
You should use PDO instead, that would be much better!
Hope this helps!
Related
I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
The full error that I keep getting when trying to run the code is:
Fatal error: Uncaught Error: Call to undefined function add_category() in /opt/lampp/htdocs/ex_starts/ch05_ex1/product_manager/index.php:73
Stack trace:
#0 {main} thrown in /opt/lampp/htdocs/ex_starts/ch05_ex1/product_manager/index.php on line 73
Below is the index.php code.
<?php
require('../model/database.php');
require('../model/product_db.php');
require('../model/category_db.php');
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_products';
}
if ($action == 'list_products') {
// Get the current category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
// Get product and category data
$category_name = get_category_name($category_id);
$categories = get_categories();
$products = get_products_by_category($category_id);
// Display the product list
include('product_list.php');
} else if ($action == 'delete_product') {
// Get the IDs
$product_id = $_POST['product_id'];
$category_id = $_POST['category_id'];
// Delete the product
delete_product($product_id);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
} else if ($action == 'show_add_form') {
$categories = get_categories();
include('product_add.php');
} else if ($action == 'add_product') {
$category_id = $_POST['category_id'];
$code = $_POST['code'];
$name = $_POST['name'];
$price = $_POST['price'];
// Validate the inputs
if (empty($code) || empty($name) || empty($price)) {
$error = "Invalid product data. Check all fields and try again.";
include('../errors/error.php');
} else {
add_product($category_id, $code, $name, $price);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
}
} else if ($action == 'list_categories'){
// GET THE CATEGORY DATA and SHOW LIST PRICE
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$categories = $db->query($query);
include('category_list.php');
} else if ($action == 'add_category') {
//GET THE CATEGORY DATA, VALIDATE INPUT, ADD CATEGORY, SHOW CATEGORY LIST
$category_name = $_POST['category_name'];
//validate
if (empty($category_name)) {
$error = "Invalid category name. Please try again.";
include('../errors/error.php');
//add category
} else {
add_category ($category_name);
}
header('Location: .?action=list_categories');
} else if ($action == 'delete_category'){
//GET CATEGORYID FROM FORM, DELETE CATEGORY, SHOW CATEGORY LIST
$category_id = $_POST['category_id'];
delete_category($category_id);
header('Location: .?action=list_categories');
}
?>
This is the code in categorydb
function add_category($category_name){
global $db;
$query = "INSERT INTO categories(categoryName)
VALUES ('$category_name')";
$db->exec($query); #Barmar
Perhaps you're not accessing the categor_db.php file you think you are? Add an echo to category_db.php (e.g. echo $query.'<br>';) and see if it prints to your page.
If that works, add the following code to index.php on lines 5 and 73:
if(function_exists('add_category'))
{echo 'add_category exists<br>';}
else
{echo 'add_category does not exist<br>';}
Confirm whether the function is defined immediately after call to category_db.php and immediately before you call the function.
Is add_category() inside a class?
If so try doing something like categorydb::add_category() or (new categorydb) -> add_category() (replacing categorydb with the actual class name)
I have a blog where I'm selecting the articles from a database using PHP. The problem is that becuase of my search terms I'm hitting an error. Here is my code:
<?php
if(isset($_GET["cat"])){
$cat = $_GET["cat"];
}else{
$cat = "all";
};
?>
<?php
if($cat == "all"){
$cat_var = "";
}else{
$cat_var = "WHERE cat = '$cat'";
}; // NOTE THIS LINE
?>
<?php
if(isset($_GET["issue"])){$issue = $_GET["issue"];}else{
$issue = "all";
};
?>
<?php
if($issue == "all"){
$issue_var = "";
$limit = 4;
}
else{
$issue_var = "AND issue = '$issue'"; // NOTE THIS LINE
$limit = 200;
};
?>
<?php
$count_posts_sql = "SELECT id FROM articles $cat_var $issue_var"; // NOTE THIS LINE
$count_posts_res = mysqli_query($con, $count_posts_sql);
$num_init_posts = mysqli_num_rows($count_posts_res);
//If None, Then Exit
if($num_init_posts == 0){
header("Location: /home");
exit();
}
...
?>
So my url would be http://website.com/articles/all/2015-10, which is what I want. However $cat_var & $issue_var is causing the error because it's selecting:
SELECT * FROM articles AND issue = '2015-10' // NO WHERE STATEMEMT IS SHOWN
How do I overcome this error?
You could get this going by sticking a WHERE 1=1 in
$count_posts_sql = "SELECT id FROM articles WHERE 1=1 $cat_var $issue_var"; // NOTE THIS LINE
This is because you start off with an AND value = 1 without starting the WHERE clause, which creates an invalid query.
Then take the WHERE out of this line and replacing it with an AND:
$cat_var = "AND cat = '$cat'";
You can initialize your where query string like this:
$where = 'WHERE 1 = 1 ';
and for there after you can concatenate depending on your inputs.
There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}
Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks