MySQL query from PHP executes only first query only - php

I have a problem in following code:
<?php
session_start();
$user_id = $_SESSION['user_id'];
?>
<?php #insert new tweets
if($user_id){
if($_POST['post_id']!=""){
include 'connect.php';
mysqli_query($conn,"Delete from post where id=".$_POST['post_id']."");
mysqli_query($conn, "UPDATE users
SET post = post - 1
WHERE username=$user_id");
}
}
header("Location: .");
?>
The first query Delete works, but the second Update doesn't, what's wrong in my code?
It redirects to header fine.

First of all, your code is vulnerable to SQL Injections. I would advise sanitizing your input first before transmitting it to that database.
I think you have a typo in your second query
UPDATE users SET post = post - 1 WHERE username=$user_id;
username should probably be user_id. Because the query can not find a matching record, it appears as if nothing is executed.
You can always verify this by checking the return value of mysqli_query.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Related

Why PDO connection sowing "SQLSTATE[HY000]: General error"?

I am using pdo connection. I am trying to run a delete query but it is showing this message in the browser
*SQLSTATE[HY000]: General error*
Here is my query:
$user_id = $_POST['user_id']; $result = query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
I don't know why happening this. Any kind of help will be appreciated.Thanks
I think there is a query() function does not exists in PHP .. It should be mysql_query or mysqli_query
Using Mysql query is bad because it is depreciated in Updated version of php
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
//So using mysqli :)
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
Per MySQL 5.5.35 source code, sql/sql_prepare.cc:
bool
Reprepare_observer::report_error(THD *thd)
{
/*
This 'error' is purely internal to the server:
- No exception handler is invoked,
- No condition is added in the condition area (warn_list).
The diagnostics area is set to an error status to enforce
that this thread execution stops and returns to the caller,
backtracking all the way to Prepared_statement::execute_loop().
*/
thd->stmt_da->set_error_status(thd, ER_NEED_REPREPARE,
ER(ER_NEED_REPREPARE), "HY000");
m_invalidated= TRUE;
return TRUE;
}
It appears that your error (SQL state HY000) will happen when there is a wrong sequence of prepare/execute statements. Double-check our logic to make sure you are properly using prepared statements, e.g properly fetching all of the results after the call to query() before calling it again.
If you cannot figure it out, isolate the problem to a minimal, complete, and verifiable example (https://stackoverflow.com/help/mcve), and post the code here.
UPDATE:
Does the problem go away (or do you at least get a meaningful error message) if you do
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
prior to the query?

mysql_fetch_array returns nothing

i was creating some script , but mysql_fetch_array returns nothing the time i have data in my database .. mysql_error(); also returns no error but i don't know what's the problem here everything is right ..
if($_POST['submit'])
{
include("connect.php");
$query=mysql_query("select * from admins where id = '$userid'");
$fetch=mysql_fetch_array($query);
$qs=$fetch['security_question'];
$an=$fetch['security_answer'];
if($qs==$question)
{
if($an==$answer)
{
header("location:panel.php");
}
}
Make sure that mysql_fetch_array return some value
Means $userid maybe do not match with any userid in your database
Use mysql_num_rows to find how may row it return
You have to check following case.
Your Form data is Posted Proper or Not ?
Your database connection is all right ?
Have you got proper userid in $userid variable ?
You have to put static userid in place of $userid variable for testing purpose.
You have to check tableName spelling and connection file spelling is correct or not?
Might above case will help you to solve your problems.

sql in php not returning anything

How do I see what is returned from a sql statement in php? I have the following function to get user name from mysql database and I use echo in another php to see the result but nothing shown.
function get_user_name($id_user) {
return mysql_result(mysql_query("SELECT username FROM user WHERE id_user = '$id_user'"));
}
echo $id_user;
$a = get_user_name($id_user);
echo $a;
Can anyone help? Thanks.
Are you echoing the get_user_name(); function?? OR are you even connected to your database? these are two things you need to check before, (if the problem remains) including an error handling method i.e. or die(mysql_error()) at the end of your query to find out the problem.
return mysql_result(mysql_query("SELECT id_user FROM user WHERE id_user = '$id_user'")or die (mysql_error()));
The error handling construct?? in mysql mysql_error() should output the problem in fairly understandable way, as to what is preventing your query not to be shown

displaying errors if mysql_query not successful

I created a debug function to email me the mysql error and query executed if a query is not successful.
I call it like this:
mysql_query($sql) or $this->debug->dbErrors($sql);
And the function is:
function dbErrors($sql = ''){
if($this->doDebug)
echo mysql_error()."<br/>".$sql;
else
#mail(hidden_email,$_SERVER['HTTP_HOST'].' Mysql Error','A error occured in '.$_SERVER['HTTP_HOST'].':<br/>'.mysql_error().'<br/>'.$sql);
}
The problem is that i'm receiving emails even when the query executes fine (at least the data is inserted and everything works out ok)
What i doing anything wrong?
Thanks
That 'or' construct may be causing issue, I would do something like:
$result = mysql_query($sql);
if (!$result) {
$this->debug->dbErrors($sql);
}
This way you are doing an explicit check to see if $result is a boolean false (query is invalid), or a resource (query is valid). The point is to only call on $this->debug->dbErrors() if there indeed is an issue, otherwise the way your code is written, every query will be emailed.
or something simple like:
mysql_query($sql) or die(dbErrors($sql));

php login script - remember me

Can anyone see anything wrong with this login script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
} else {
echo $username, $pass;
}
To explain:
At the moment the script is allowing anything through. In other words the query is returning true for any username and password that are passed to it.
I've put the echo statement just as a check - obviously the script would continue in normal circumstances!
I know that the connect class and login_connect method are working because I use them in a register script that is working fine. depException is just an extension of the Exception class.
The function login() is part of the same class that contains register() that is working fine.
I know that the two variables ($username and $pass) are getting to the function because the echo statement is outputting them accurately. (The $remember variable is not needed for this part of the script. It is used later for a remember me process).
I'm stumped. Please help!
UPDATE
Thanks for those responses. I was getting confused with what the query was returning. The complete script does check for how many rows are returned and this is where the checking should have been done. Everything is now working EXCEPT for my remember me function. Perhaps someone could help with that?!?! Here is the full script:
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
}
if ($result->num_rows>0) {
$row = $result->fetch_assoc();
//assign id to session
$_SESSION['user_id'] = $row[user_id];
// assign username as a session variable
$_SESSION['username'] = $username;
// start rememberMe
$cookie_name = 'db_auth';
$cookie_time = (3600 * 24 * 30);*/ // 30 days
// check to see if user checked box
if ($remember) {
setcookie ($cookie_name, 'username='.$username, time()+$cookie_time);
}
// If all goes well redirect user to their homepage.
header('Location: http://localhost/v6/home/index.php');
} else {
throw new depException('Could not log you in.);
}
}
Thanks very much for your help.
UPDATE 2!
Thanks to your help I've got the main part of this script working. However, the remember me bit at the end still doesn't want to work.
Could someone give me a hand to sort it out?
$username, $pass and $remember are all short variable names that I assigned before passing them to the function to save writing $_POST['username'] etc. everytime. $remember refers to a checkbox.
What does $conn->query() return, a MySQL resource object like mysql_query() does? If so then it'll always compare "true". mysql_query() only returns FALSE if the query completely fails, like it has a syntax error or a table doesn't exist.
To check if you got any results you need to try to fetch a row from the result set and see if you get anything, via whatever your equivalent of mysql_fetch_row() is.
Important: Your script is vulnerable to SQL injection attacks, or even just odd usernames like o'neil with an apostrophe. You should escape all variables in a query with mysql_real_escape_string() (or equivalent) to make sure your query doesn't get messed up by special characters. Or, even better, use prepared statements which look like
select * from login where username=? and password=sha1(?)
Re: UPDATE
Variables from a form are available via either $_GET or $_POST, depending on which method was used to submit the form. Try if (isset($_POST['remember'])) to see if that check box was checked.
Important: I see that you tried to use a bare $remember to see if the check box was checked. That suggests to me that you are trying to take advantage of the register_globals feature in PHP which makes your GET and POST variables accessible via regular variable names. If that is the case you should heed the warning in the PHP manual!
WARNING
[register_globals] has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Use $_GET and $_POST instead. I could tell you how to make if ($remember) work, actually, but given the inherent evil-ness of register_globals I'm not gonna! ;-)
Your query is open for sql-injections...
SELECT * FROM users WHERE
username = '' OR 'a' = 'a'
AND password =
sha1('guessAnyPassword')
I'd also check your result, and base the action on how many records were returned.
if (mysql_num_rows($result) > 0)
In php most queries only return False if there was an error executing them. Your query is returning a value, probably an empty array of values. This is not a false value as far as your if statement is concerned.
Check how many rows are returned. The function to do this will depend on your abstraction layer (connect class etc...)

Categories