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.
Related
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) {
...
}
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()
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.
Probably a simple one so please excuse me.
At the top of my page I include a file:
<?
require("common.php");
?>
Later on in my code I do the following:
$stmt = $db->prepare($query);
$result = $stmt->execute();
$result = $stmt->fetchAll();
(the db connection files being in my include file).
This works fine, until I try and make the code a function For example: If I do
function doAQuery(){
$stmt = $db->prepare($query);
$result = $stmt->execute();
$result = $stmt->fetchAll();
}
It can't find the db details. Please can someone explain why?
It's not a syntax issue. Your $db and $query variables are not available to your function scope. You can make them available by declaring global $db, $query as the first line of your function.
It's because $db is a global variable. PHP ignores it in the function scope unless you explicity declare it should be used.
function doAQuery() {
global $db;
$stmt = $db->prepare($query);
$result = $stmt->execute();
$result = $stmt->fetchAll();
}
Take a look at how variables scope works in PHP.
Pass Query string to function,
function doAQuery($query){
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Cannot use call_user_func_array on mysqli_stmt object
I have a piece of mysqli code which is outputting a warning in this line of code:
if (!$stmt = $mysqli->prepare($questionquery)) {
die("Error preparing statement: $mysqli->error");
}
The warning is:
Warning: Wrong parameter count for mysqli_stmt::bind_param() in ... line 80
Below is main code:
// Make the referenced array
$referencedArray = make_values_referenced(array_merge(
array(str_repeat("ss", $numTerms)), // types
$termArray, // where
$termArray // order by
));
// ...or die() is evil in production but I shall assume we are debuggin so I won't complain
if (!$stmt = $mysqli->prepare($questionquery)) {
die("Error preparing statement: $mysqli->error");
}
// Bind parameters
if (!$stmt->bind_param($referencedArray)) {
die("Error binding parameters: $stmt->error");
}
You can call the method directly:
$stmt->bind_param($referencedArray);
EDIT: Actually I'm mistaken. You need call_user_func_array for variable number of parameters. See this answer for a solution: https://stackoverflow.com/a/5108167/163024
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 years ago.
I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object?
class shoutbox {
private $db;
function __construct($dbname, $username, $password, $host = "localhost" )
{ # db conections
try {
$this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
function getShouts()
{
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');
return $sql_shouts->fetch(PDO::FETCH_OBJ);
}
}
Look carefully at the documentation for PDO::query, particularly the "Return Values" section:
PDO::query() returns a PDOStatement
object, or FALSE on failure.
The important bit is "FALSE on failure". FALSE is not an object, so calling ->fetch() is bad news.
The error is probably due to your use of "==" comparison operator. In SQL, it's just "=".
You should test that the $sql_shouts is not false, and then do something smart with the error, if there was one:
<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
$errorInfo = $this->db->errorInfo();
//log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);
I would say that your query is not executing due to incorrect syntax. You should really check PDO's errorinfo static function to see if the query errored out or not.
Here is a potential correct SQL statement:
$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');
I believe Time is a reserved word in MySQL I would recommend using a different name but encasing it in backticks will alleviate that issue. 1 equal sign is used for mysql, not two. But yea, look into the errorinfo function to determine if your query failed due to a syntax error and handle it gracefully.
It happens when the table doesn't exist also. make sure it actually exists, and isn't just a holder in the database due to hard drive errors.
When that happens I suggest you recreate the database/table.
I got this error message due to a silly mistake with brackets. It was nested inside an if statement and just didn't see it.
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var)->fetchField());
It took me a while to work out that I didn't close the db_query bracket in the right place. Maybe it helps someone else staring at this wondering wth. Correct:
db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var))->fetchField();