Sql query isnt executed [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I am modifying my code against sql injection. Commented is old code (2 strings).
Uncommented is new. But i see no effect of the code. Database isnt updated and debug info isnt printed. My server runs php 5.6. Neither "Success" nor "Error" is printed.
Heres the code:
add_answer.php
// Insert answer
//$sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_email, a_answer, a_img, a_datetime)VALUES('$id', '$Max_id', '$a_name', '$a_email', '$a_answer', '$a_img', '$datetime')";
$stmt = $dbh->prepare("INSERT INTO $tbl_name (question_id, a_id, a_name, a_email, a_answer, a_img, a_datetime)
VALUES (:qid, :aid, :nam, :eml, :ans, :img, :datet)");
$stmt->bindParam(':qid', $id);
$stmt->bindParam(':aid', $Max_id);
$stmt->bindParam(':nam', $a_name);
$stmt->bindParam(':eml', $a_email);
$stmt->bindParam(':ans', $a_answer);
$stmt->bindParam(':img', $a_img);
$stmt->bindParam(':datet', $a_datetime);
$result2=$stmt->execute(); $stmt->debugDumpParams();
//$result2=mysql_query($sql2);
if ($result2)
echo "Success";
else
echo "Error";

Not sure it will work, but maybe try hard coding the table name rather than using a variable for it in the query.

Related

PHP not showing MySQL results with variable in query [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined issue [duplicate]

This question already has answers here:
Error when preparing a multiple insert query
(5 answers)
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
I am very unsure at why I am getting such an error with my code
try {
$stmt = $connection->prepare("INSERT INTO table (path, title, era, information)
VALUES (:path, :title, :era, :information)");
$stmt->bindParam(':path', $fname);
$stmt->bindParam(':title', $Name);
$stmt->bindParam(':era', $Era);
$stmt->bindParam(':descrip', $Description);
// insert row
$stmt->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
echo "Upload Successful";
}
I have tried so many different options and I just cant fix the error
$fname=$_FILES["userfile"]["name"];
$Name =$_POST["name"];
$Era =$_POST["era"];
$Description =$_POST["info"];
these are the variables I used if that helps in solving my issue
You define the values ':path, :title, :era, :information' in your prepare statement but try to set a value for the field ':descrip' later on. Because this field is not defined in the prepare call you get that error.
Use ':information' instead of ':descrip'.

MySQLi Insert Statement placing NULL for variable [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
So I have the following code which is used to add a row to the respondent table, all working except when trying to add the value in of Brand:
$brand = 'Central';
function new_respondent() {
global $link;
$proc = mysqli_prepare($link, "INSERT INTO trespondent (brand, code) VALUES (?, uuid());");
mysqli_stmt_bind_param($proc, "s", $brand);
mysqli_stmt_execute($proc);
$respondent_id = mysqli_insert_id($link);
mysqli_stmt_fetch($proc);
mysqli_stmt_close($proc);
mysqli_clean_connection($link);
}
This code works (to a point) adds a row in the table and adds in the UUID no problems but brand is going in as NULL - I'm trying to work out if I am missing something very obvious here!
Any and all suggestion welcome.
You need to add $brand to your global, since it's outside of the function:
global $link, $brand;
Alternatively, you can modify your function to accept $brand as parameter:
function new_respondent($brand) {
...
}

PHP: How to pass an array to bind_param [duplicate]

This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 2 years ago.
I've been trying to figure this out.
$insertSql = 'INSERT INTO table (id,date,name,numFarts) VALUES (?,?,?,?)';
$values = (1,'0000-00-00 00:00:00','Bob',5);
$bind_param_str = ('issi');
if ($stmt = $db->prepare ($insertSql)) { // $inserSql is a pre-writted sql insert
$stmt->bind_param($bind_param_str,$values);
$stmt->execute();
$stmt->close();
}
This doesn't work, but I can't think of any other way to pass $values into bind_param()
Any ideas?
For any function that you need to pass an array as the argument/s you can use call_user_func_array.
In this example:
array_unshift($values,$bind_param_str);
call_user_func_array(array($stmt,'bind_param'),$values);
Don't ask me why you need array($stmt,'bind_param') instead of $stmt->bind_param. Has something to do with the syntax of -> I'm sure.
The clean solution (PHP5.6+) :
$stmt->bind_param($bind_param_str, ...$values);

PDO prepared statement for update doesn't work properly [duplicate]

This question already has answers here:
What is the difference between bindParam and bindValue?
(7 answers)
Closed 7 years ago.
This is my php code:
public function update($table,$fields_and_values,$condition_field,$condition_field_value)
{
$query="UPDATE $table SET ";
foreach($fields_and_values as $field=>$value) $query.=($field."=:".$field." ,");
$query.=" ";
$query=str_replace(", "," WHERE ",$query);
$query.=($condition_field."='".$condition_field_value."'");
echo $query;
$stmt=$this->conn->prepare($query);
foreach($fields_and_values as $field=>$value) $stmt->bindParam(":".$field,$value);
$stmt->execute();
}
and this is how i call the function in my class:
$db=new db_connection('localhost','root','','maps');
$db->connect();
$arr=array('username'=>'testfromnewclass3','password'=>'123456');
$db->update('users',$arr,'username','term');
$db->disconnect();
It doesn't matter what the other functions like disconnect do! They work correctly.
My problem is that when this command executes, both username and password become 123456 !
And this is what i get from that echo $query:
UPDATE users SET username=:username ,password=:password WHERE username='term'
Is something wrong with my function? and if so how can i fix it?
Use $stmt->bindValue($field, $value);
instead of $stmt->bindParam(":".$field,$value);
Check this to understand difference between PDOStatement::bindParam() and PDOStatement::bindValue()

Categories