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.
Related
I have the following teachers.php page, developed by a freelancer. He says it works on his localhost and he is using php 5.3, but the only reason it doesn't work when we upload it to our servers, and BlueHost has v.4.3 is because of the older version.
I am awaiting a response on how he can resolve this, assuming he will say he can, but would be interested in any responses/suggestions/solutions.
What is causing the error (what lines of code) and what are the best solutions to get around this?
the page in question does some teacher tracking:
The start of the code in the page is as follows:
<?php
require_once("scripts/connect_db.php");
session_start();
if(!isset($_SESSION['teacher'])) header('Location: teacher_login.php');;
$result="";
if (isset($_POST["logout"])) {
session_destroy();
header('Location:index.php');
}
$err = "";
if (isset($_POST["add_class"]) && !empty($_POST['class_names']) && $_SESSION['teacher']) {
$class_name = mysqli_real_escape_string($con,$_POST['class_names']);
$school_pin = $_SESSION['teacher_school_pin'];
$teacher_username = $_SESSION['teacher_username'];
$teacher_id = $_SESSION['teacher_id'];
$query = mysqli_query($con,"INSERT INTO classes (teacher_username, teacher_id,school_pin, class_name)
VALUES('$teacher_username','$teacher_id', '$school_pin', '$class_name')");
}
if (isset($_POST["track_button"])) {
$var = mysqli_real_escape_string($con,$_POST['user_name']);
$quiz = #mysqli_real_escape_string($con,$_POST['quiz']);
$school_pin = mysqli_real_escape_string($con,$_POST['school_pin']);
$class_name = #mysqli_real_escape_string($con,$_POST['class_name']);
$top = #mysqli_real_escape_string($con,$_POST['top']);
$array_one = comma_separated_to_array($var);
$query = array();
if($quiz != "non"){
array_push($query," quiz_id=".$quiz." ");
}
if(count($array_one) != 0){
array_push($query," username IN ('".implode("','",$array_one)."') ");
}
if(!empty($class_name)){
if($class_name !== "all"){
array_push($query," class_name='".$class_name."' ");
}
}
if(!empty($school_pin)){
array_push($query," school_pin='".$school_pin."' ");
}
if($quiz == "non"){
$result = mysqli_query($con,"SELECT DISTINCT username FROM quiz_takers WHERE ".implode(" AND ",$query)." ORDER BY percentage DESC LIMIT ".$top);
if(!$result)$err = "Enter Your student data to Track, Please!";
}else{
$result = mysqli_query($con,"SELECT * FROM quiz_takers WHERE ".implode(" AND ",$query)." ORDER BY percentage DESC LIMIT ".$top);
if(!$result)$err = "Enter Your student data to Track, Please!";
}
if(#mysqli_num_rows($result) == 0){
$err = "No Result Found!";
}
}
$all_classes = mysqli_query($con,"SELECT class_name FROM classes WHERE teacher_username='".$_SESSION['teacher_username']."'");
I try to update the data in the database, but when I run the code, there is no error message appear, looks like its a logical error but I still don't have any clue about what is happening with my code.
Here is the code
<?php
include("conn.php");
SESSION_START();
if($_SESSION["loggedin"]!="true"&& $_SESSION['login'] != '')
header("location:login.php");
$aid = $_SESSION["usr"];
$result = mysql_query("select r.CustomerID from customer c inner join results r on r.CustomerID = c.CustomerID where c.Username = '".$aid."' ");
if (false === $result) {
echo mysql_error();
}
$row = mysql_fetch_assoc($result);
?>
<?php
if (isset($_POST["submitbtn"]))
{
$bookid = $_POST["bookid"];
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
$query = mysql_query("UPDATE `results` SET LP = '$LP', budget = '$budget', SmokeP = '$smokep', sp_req = '$spreq'
WHERE results.BookID = '".$bookid."' and results.CustomerID = '".$result."'");
if (false === $query)
{
echo mysql_error();
}
?>
<script type = "text/javascript">
alert("Amendment Saved!!");
</script>
<?php
}
?>
Is the error coming from the select query? Or the if statement for the submitbtn went wrong?
First of all you cant put session start here
You must put it on the first line after open php tag
Second
update res='$ new_value' where ...
Tell me if it's not usefull to try another solution
I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.
I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.