Strange prepared statements error - php

Here is how my statement looks like.
$stmt = $this->db->prepare("
select q.id
from questions q
left outer join (
select max(chk_date) as questions_last_chk_date
FROM last_check_date
where user_id = ?
AND chk_token=?) lcd
on q.add_dt > lcd.questions_last_chk_date
WHERE q.author_id<>?
") or die($this->db->error);
$stmt->bind_param("isi", $_SESSION["userID"], "q", $_SESSION["userID"]) or die($stmt->error);
I got 2 questions
1) Getting error message
Fatal error: Cannot pass parameter 3 by reference
why this error occurs? BTW, I know that last_check_date table is empty but I think it's not related with this problem.
2) On windows, getting error message table last_check_date doesn't exist, but I 100% know that there is no typo, and table exists. I tried the same query with Navicat - db amanger application and got result. But when I try with PHP getting this error. On remote Linux server it works, and getting error message in question 1. Tried to restart mysql service, rename to other name and change name back to previous. No success! How can I fix that problem?

You have to put q into a variable.
FYI, try not to use string values equals to tables alias or references. You are passing value of q when you have a table with the q alias. This is not an error, but maybe could be very confusing in case you need to do an echo of your query.

Related

Pdo error with invalid parameters

I have an error since yesterday on my crud and I'm becoming crazy.
For editing entries in my database, I have two files:
edit.php with the editing form identified by the parameter id
see code
doedit.php that actually modify the entry in database
see code
and the warning returned is :
PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in /Users/joseteixeira/Sites/TP-PHP/admin/doedit.php on line 47
Any idea on what might have gone wrong ?
In your doedit.php, you have this line in your query:
`p` = p,
Change this to:
`p` = :p,
Your error says that "parameter" was not defined, so kindly remove parameter from bindValue function.
$statement->bindValue(":slug", $slug);
In your SQL statement please use
p = :p
You have missed: while assigning value.
I think you forgot to put a : before p (should be :p) on 28 number line in your doedit file.

PHP / mysqli: Prepared Statements with num_rows constantly returning nothing

In my test-surroundings there is a database containing some Person Information (Name, E-Mail, Adress etc.). These Informations can be inserted by anyone into the database via a form. In the background they are inserted with a parameterized INSERT into the database after submission.
What I now would like to do is to detect if some person tries to insert the same values into the database again, and if he does, not inserting the new values and instead showing an error message. (So every person name in the database is unique, there are no multiple rows linked to one name).
I had a numerous number of ideas on how to accomplish this. My first one was to use a query like REPLACE or INSERT IGNORE, but this method would not give me feedback so I can display the error message.
My second attempt was to first do a SELECT-query, checking if the row already exists, and if num_rows is greater than 0, exit with the error message (and else do the INSERT-part). For this to work I will have to use parameterized queries for the SELECT too, as I´m putting some user input into it. Figuring that parameterized queries need special functions for everything you could normally do with way less lines of code, I researched in the internet on how to get num_rows from my $statement parameterized-statement-object. This is what I had in the end:
$connection = new mysqli('x', 'x', 'x', 'x');
if (mysqli_connect_error()) {
die("Connect Error");
}
$connection->set_charset("UTF-8");
$statement = $connection->stmt_init();
$statement = $connection->prepare('SELECT Name FROM test WHERE Name LIKE ?');
flags = "s";
$statement->bind_param($flags, $_POST["person_name"]);
$statement->execute();
$statement->store_result();
$result = $statement->get_result(); //Produces error
if ($result->num_rows >= 1) {
$output = "Your already registered";
} else {
$output = "Registering you...";
}
exit($output);
After all, I can´t get why mysqli still won´t give me num_rows from my statement. Any help is appreciated, thanks in advance!
Oh, and if you guys could explain to me what I have to do to get affected_rows,that would be awesome!
EDIT: I know I could to this by using unique constraints. I also found out that I can find out if INSERT IGNORE skipped the INSERT or not. But that won´t answer my complete question: Why does the SELECT num_rows alternative not work?
ANOTHER EDIT: I changed the code snippet to what I now have. Although my mysql(i)-version seems to be 5.6.33 (I echo´d it via $connection->server_info) get_result() produces the following error message:
Fatal error: Call to undefined method mysqli_stmt::get_result() in X on line X (line of get_result)
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. Note that if the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.
Also make sure that you declare ->store_result() first. Moreover the function doesn't work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually.
EDIT:
If nothing from the suggestions does not work for you, then I would propose to rewrite your SQL query:
SELECT `Name`, (SELECT COUNT(*) FROM `Persons`) AS `num_rows` FROM `Persons` WHERE `Name` LIKE ?
This query will return the total number from your Persons table, as well as Name, if exist.

Php postgresql variables in a query

I'm trying to get the right syntax for the following. In this case $post_pub = 1
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL" FROM "Publications" where "Pub_ID"="$post_pub"';
Php throws an error: column "$post_pub" does not exist
I've stumbled across pg_query_params, this feels like the right direction, but I need some help. How can I get this to work?
I never used pg_connect though I think you need something like this:
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL"
FROM "Publications"
where "Pub_ID"=$1 ';
$result = pg_query_params($dbconn, $sql, array($post_pub));
the problem is double quotes around variable. Postgres understands it as "database object" name, in this part of query, a column. to avoid it, try using:
$sql='SELECT "Publications"."Pub_ID", "Publications"."ART_TITEL" FROM "Publications" where "Pub_ID"='."$post_pub";
also consider moving to PDO - such usage is a straight invitation for sql injection. Setting$post_pub to 0 or (delete from Publications)" will delete all data if user has enough right, for example.

mysqli_num_rows() expects paramter though an earlier query on the same page works

I am getting an error when querying a table in my MySQL database. It's the standard one with mysqli_num_rows when there is no value in the variable that's being passed:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in folder/file.php on line 29
Problem is I can't find the syntax error. I've looked at it a ton of times. Here's what my code is:
$sql_messages = "SELECT * FROM messages WHERE to='$userid'";
$result_messages = $mysqli->query($sql_messages);
$num_rows_messages = mysqli_num_rows($result_messages);
I tried a fetch array but that gave me the similar error. Nothing is getting passed into $result_messages I suppose. I echo'ed out $userid and that has a value and I've checked my database and there is a table 'messages' with a field 'to'. I'm connected to the right database because I have this code before this query:
$sql="SELECT * FROM users WHERE firstname='$firstname' && lastname='$lastname'";
$result = $mysqli->query($sql);
$row = mysqli_fetch_array($result);
And that works fine. It is the third query on the page, is there some sort of limit? Does anyone see a syntax error that I'm overlooking? Thanks, sorry if it's a small little error!
It's because $mysqli->query() returned boolean FALSE, which, according to the mysqli::query() docs, it does when an error happens. You can get more detail on the error by accessing $mysqli->errno and $mysqli->error.
I'm guessing that the root of the problem lies in the query which references a column called to, which is a MySQL reserved word. Try surrounding the word to in your query with backticks. Like this:
$sql_messages = "SELECT * FROM messages WHERE `to`='$userid'";
Really, though you should avoid naming columns and tables reserved words. Consider renaming the column if feasible.

MySQL: error when query returns no results?

I have a query that looks like this:
SELECT number
FROM table1
INNER JOIN table2
WHERE name = 'stack_overflow' AND table1.id = table2.id
AND user_id = 5
This returns a number. It does the right thing, but when inside name I pass a name that does not exist in db, PHP gives me an error. This is how I am executing it:
$stmt = $this->db->prepare($sql);
$stmt->execute();
$x = $stmt->fetchColumn();
I always get the correct $x value when the name exists in the table, however when it doesn't, I get the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'name_that_is_not_in_table'
No idea....
Try to pass name in this way:
SELECT number
FROM table1
INNER JOIN table2
WHERE name = ? AND table1.id = table2.id
AND user_id = 5
$stmt = $this->db->prepare($sql);
$stmt->execute(array($name));
$x = $stmt->fetchColumn();
Sounds like you need to check how many rows are returned first... if none, notify the user. If it DOES have a returned row count, then get the name column as you are expecting.
Additionally, you should clarify the alias.column in your queries as anyone new doesn't have to guess which table a given column comes from... Such as your user_id and name columns. (and "name" might be a reserved word and cause the choke... so you might want to wrap it in tick marks
`name`

Categories