Can't seem to get query to work? - php

<?php
error_reporting(E_ALL);
session_start();
include ('connect.php');
if(!empty($_POST['budgetbox']))
{
$budgetboxvar = $_POST['budgetbox'];
$sql="INSERT INTO users WHERE username = '".$_SESSION['usernamebox']."'(budget) VALUES ('$budgetboxvar')";
mysqli_query($db,$sql);
}
?>
Does anyone have an idea why the code above doesn't work ? It seems like the code works if I leave the code below out. I'm sorry but I can't seem to figure out how this is not correct ? I'm not getting any error messages either.
When I take out the WHEN username is SESSION usernamebox part out.. the query does input into my database, only not in the field of a logged in user..
I tried to echo something if the query succeeded but it doesn't show anything either.. Which means the query can't be executed (I think). Can't figure out why though(it's hard being a noob sometimes)
Thank you in advance, hope you can help !

If I understand you correctly, something like this:
$sql = "UPDATE users SET budget='".$budgetboxvar."' WHERE username = '".$_SESSION['usernamebox'];

if(!empty($_POST['budgetbox']))
{
$query = $db->prepare("UPDATE users SET budget=? WHERE username=?"); ///statements voorbereiden
$budgetboxvar = $_POST['budgetbox'];
$name = $_SESSION['usernamebox']; //var toekennen
$query->bind_param("ss", $budgetboxvar, $name);
$query->execute();
echo"Thank you for entering your budget!";
}
And.. i changed the database column "budget" to VARCHAR64

Related

PHP How to validate URL with id ungiven parameter?

I have a website where I can show a single post with view_post.php?id=1 but when I try to show a post with for example view_post.php?id= or view_post.php?id it shows nothing.
Then I tried to Log the Database Query like this:
$query = "SELECT * FROM posts WHERE id='$postIdFromUrl'";
$stmt = $db->query($query);
if (!$stmt) {
$_SESSION["test"] = $stmt;
redirect_to("Blog.php");
}
It doesnt show anything as the query is valid.
So my question is how to validate that. I tried a lot of things with e.g. URL Validation... nothing worked.
I would be very happy if someone could send me a code that can check for that.
Thanks very much in advance!
just check if id exists or its empty before u do anything
if (isset($_GET['id']) && !empty($_GET['id'])) {
//do your original code
} else {
redirect_to("Blog.php");
}

Simple PHP/Ajax for a search suggestion program - only displaying results from database typed in full

So my problem is simple. I'm a PHP beginner (noob programmer in general, started 3 months ago) and I've been following some tutorials on how to build a "search suggestion" system, that checks in the database if what you're typing is like anything in it and displays the results real time with AJAX.
It is working partially. When I type in a full username, for example, it displays the result. But not when I type half of it, or the first letter.
<?php
require 'connect.php';
if (isset($_GET['searchText'])) {
$searchText = $_GET['searchText'];
}
if($query = $db->prepare("SELECT user_name FROM users WHERE user_name LIKE ?")) {
$query->bind_param('s', $searchText);
$query->execute();
$query->bind_result($searchTextResult);
while ($query->fetch()) {
echo $searchTextResult;
}
}
?>
Also, since I'm a total noob I'd love to have any suggestions on the code just to know if I'm employing good practice in general. I heard binding and mysqli are recommended, so I'm trying to stick to them and I rarely get any criticism at all.
The sql query which search a parameter partially would be like this:
"select user_name FROM users WHERE user_name LIKE CONCAT('%',?,'%')"
Thanks everyone for all the answers. This was my first time on StackOverflow and I loved it. I hope I can return the favor someday.
All I had to do was add "%" to the $searchText var right in the beginning and everything ran smoothly.
The correct code is now as follows:
<?php
require 'connect.php';
if (isset($_GET['searchText'])) {
$searchText = $_GET['searchText'] . '%';
}
if($query = $db->prepare("SELECT user_name FROM users WHERE user_name LIKE ?")) {
$query->bind_param('s', $searchText );
$query->execute();
$query->bind_result($searchTextResult);
while ($query->fetch()) {
echo $searchTextResult . "<br />";
}
}
?>

Problems updating MySQL, "username" in a table using PHP

I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

Posting data from Database

I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.

Categories