MySQLi Insert Statement placing NULL for variable [duplicate] - php

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) {
...
}

Related

$stmt variable contains null using prepare function [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 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 4 years ago.
$stmt variable is null means it doesn't contain my query even though connection($con) to the database is created.
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\WebServersAndroid\includes\DbOperations.php:24 Stack trace: #0 C:\xampp\htdocs\WebServersAndroid\v1\registerUser.php(12): DbOperation->createUser('syed', '1997') #1 {main} thrown in C:\xampp\htdocs\WebServersAndroid\includes\DbOperations.php on line 24
error occurs in bind_param maybe because there is no query to store data to. Please tell me what is the problem and why $stmt is null. Thank you
class DbOperation{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
function createUser($name,$usn){
$query = "INSERT INTO 'test_col'('name','usn') VALUES (?,?); ";
$stmt = $this->con->prepare($query);
echo $stmt;
if($stmt != null)
{
$stmt->bind_param("ss",$name,$usn);
if($stmt -> execute())
{
return true;
}else{
return false;
}
}
else{
echo "in else";
}
}
}
I think this code generates a lot of errors.
$query = "INSERT INTO 'test_col'('name','usn') VALUES (?,?); ";
values (?, ?) expects 2 values to be bind later.
While this code
`$stmt->bind_param("ss",$name,$usn);`
binds 3 parameters which trigger an error in binding.
Next, the use of single/double quotation mark is interpreted by MySQL as String literal as stated in documantation
As a result, 'test_col'('name','usn') causes error, you should use ` or just leave the name of table and columns instead of using single quotation mark (') which translate your table name, database name, and/or column name to string instead of reference.

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'.

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()

Function not working [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)
Closed 9 years ago.
The following function is not working and i cannot see why.
function nuevoContacto($_POST) {
try {
include('func/usarBases.php');
$mensaje="INSERT INTO `t_contactos`(`id_c`, `nombre`, `telefono`, `telefono2`, `corto`, `celular1`, `celular2`, `email`, `puesto`, `id_a`) VALUES (NULL,'$_POST[nombre]','$_POST[tel1]','$_POST[tel2]','$_POST[corto]','$_POST[cel1]','$_POST[cel2]','$_POST[email]','$_POST[puesto]','$_POST[id_a]')";
$hacerConsulta = $base->prepare($mensaje);
$hacerConsulta->execute();
}
catch( PDOException $e) {
echo "<p>Error Connection: " .$e->getMessage()."</p>";
}
$hacerConsulta=null;
}
Once it is called the code breaks and nothing further is executed.
but when you use it inside the main code it works
Sorry i reedited the source and then is still not working, in the include usarBases.php is the conector pdo called $base
What it have to be
function nuevoContacto($base)
{
$sql = "INSERT INTO t_contactos VALUES (NULL,?,?,?,?,?,?,?,?,?)";
$data = array(
$_POST['nombre'],
$_POST['tel1'],
$_POST['tel2'],
$_POST['corto'],
$_POST['cel1'],
$_POST['cel2'],
$_POST['email'],
$_POST['puesto'],
$_POST['id_a']
);
$stmt = $base->prepare($sql);
$stmt->execute($data);
}
have to be called with $base as a parameter instead of $_POST
You're lacking a database connection in your function. Add the following to the very beginning of your function:
global $base;
When you add global $base to your function you'll be able to use it within your function without having to re-write the whole thing.
Unrelated note, but worth mentioning.
You are open to SQL injections and you're not using prepared statements as you should. You should be using placeholders and binding them later instead of passing they directly into your query.
And a tip for next time:
State in your question what isn't working. What your expectation is and what actually happens.

Categories