Save and iterate array in php-mysql - php

I have the following code to save an array in my DB:
public function agregarBolsasModel($datos, $tabla) {
$datosL=array($datos["valoresBox"]);
$stmt = Conexion::conectar() -> prepare("INSERT INTO $tabla(lote, caja, bolsa)VALUES(:one, :two, :three)");
for($p = 0; $p < sizeof($datosL); $p++) {
$stmt -> bindParam(":one", $datos["loteNum"], PDO::PARAM_INT);
$stmt -> bindParam(":two", $datos["cajaNum"], PDO::PARAM_INT);
$stmt -> bindParam(":three", $datosL[$p], PDO::PARAM_INT);
$stmt->execute();
}
$stmt->close();
}
The value of three is an array like [1,2,3] where I don't know the size cause it's a dynamic array, but I can't save the data in my DB, also when I tried to save the data I received the following error:
Fatal error>: Uncaught error: Call to undefined method PDOStatement::close()
what is my mistake? How could I do to fix that?
Thanx

PDO doesn't have a "close" function. You can do
$this->db = null;
In your case, on $stmt

Use $stmt = null;
instead of $stmt->close();

Related

mysqli array fetching is not getting data

I have to fetch result in single row but I can't run multiple rows. How can I fix this?
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
I Got Result Like Wise This
{"ID":2,"Name":"Anju"}
But i need to get all user result .my code is here
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
$stmt->close();
return $result;
}
I got the error
Fatal error: Call to a member function fetch_array() on a non-object in line 5
The line is:
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))
my expecting result is
{"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bindValue(1, $id);
Try that way
And try to fetchAll instead of fetch_array
You could make following correction.
Change
$rows->fetch_assoc(MYSQLI_ASSOC)
to
$rows->fetch_assoc()
It should look like
if ($stmt->execute()) {
$rows = $stmt->get_result();
$result = array();
while ($row = $rows->fetch_assoc()){
$result[] = $row;
}
$stmt->close();
return $result;
} else {
return NULL;
}
Suggestion : Always specify the list of columns in your SELECT, which makes query execution faster.
Please read php manual

Cannot execute prepared statement "Fatal error: Call to a member function prepare() on null" error

So I have this code
$lang=new language();
$default_language=$lang->getLanguage(0);
$currencies = new currency();
$currencies = $currencies->getCurrencies();
getCurrencies() and getLanguage() are in another file with classes.
public function getCurrencies() {
$curr=new record();
return $curr -> getRecords('currencyTable','currency_order',array("currency_id","currency_name"));
}
public function getLanguage($record) {
$lang=new record();
return $lang->getRecord('languageTable',$record,'lang_order','*');
}
And getRecords and getRecord are public functions it the record class
I keep on getting the error
Fatal error: Call to a member function prepare() on null
Referring to the query of the getRecords functions.
I dont know how to fix this. Does this has to do with the connection to the database?
Also, the weird part is that if I remove the
$lang=new language();
$default_language=$lang->getLanguage(0);
part, this error goes away. Any help? Is the error in the $default_language=$lang->getLanguage(0); line and this is why it is messing up the database connection, resulting to this error?
Thanks
EDIT
Here are the getRecord and getRecords
public function getRecords($table,$sorder,$field_names) {
$conn = db::open();
//- build string of field names
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//end up with field1, field2... or *
//soreder is a field, contains int like 1 2 3
//- run statement
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
and
public function getRecord($table,$record,$sorder,$field_names) {
$conn = db::open();
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//same things for $field_string and $sorder
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." LIMIT ? OFFSET ?");
$stmt->bindValue(1, 1 , PDO::PARAM_INT);
$stmt->bindValue(2, $record, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
}
I fixed an error. In getRecord I had LIMIT 1 and I fixed it as above. I still get the same error about the getRecords line : $stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
Any thoughts?
Thanks
Your database connection failed. The error is not in your posted code. The error in your code is when the statement is being prepared.
Ex: $statement = $dbh->prepare("SELECT * FROM some_table"). I would recommend throwing an exception to see what's going wrong with your connection. You can do this by adding the options to your pdo initialization. array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
try{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB,
MYSQL_USERNAME,
MYSQL_PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(Exception $e){
echo $e->getMessage();
}
Hope this helps

When I run the PDO script alone it work fine but when I put it in a function it will not work

When I run the PDO script alone it runs just fine But when I run it in a function I get this error Fatal error: Call to a member function prepare() on a non-object. I can not figure out why it is happening.
$pid = 6;
$custid = 1;
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
$pid = 6;
$custid = 1;
function test($custid,$pid){
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;
}
echo test($custid,$pid);
The variable $db is not visible inside your function. you need to add
function test($custid,$pid){
global $db;
[...]
}
inside your function or you should pass the db object to your function via parameter:
function test($db, $custid,$pid){
[...]
}
another nice way ist to work with the factory patterns:
create a class db with a static method dbFactory and call it whenever you need to access your db
class db {
public static function dbFactory($host, $dbase, $user, $pass) {
$pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
$db = db::dbFactory('localhost','mydbname','myusername','mypassword');

Mysql statement inside a function doesn't work

I have a MySQL statement in a function but somehow it doesn't work. I get the following error:
Fatal error: Call to a member function
prepare() on a non-object in
D:\xampp\test.php on line 7
function isloggedin($getcookiedata) {
$data = explode("|", $getcookiedata);
$userid = $data[0];
$md5password = $data[1];
$sql = "SELECT user_id, username, email, newsletter, user_group FROM users WHERE user_id = ? AND md5password = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $userid, $md5password);
$stmt->execute();
$stmt->bind_result($r_userid, $r_username, $r_email, $r_newsletter, $r_user_group);
$stmt->store_result();
$checker = $stmt->num_rows;
$stmt->fetch();
$stmt->close();
}
When I just do the SQL statement outside a function, it works. But not inside the function.
If $mysqli is a global you're defining somewhere, you need to pull it into your function's scope with:
function isloggedin($getcookiedata) {
global $mysqli;
...
}
See PHP - Variable scope

PDO Stored Procedure return value

I'm working with a SQL Server stored procedure that returns error codes; here is a very simple snippet of the SP.
DECLARE #ret int
BEGIN
SET #ret = 1
RETURN #ret
END
I can get the return value with the mssql extension using:
mssql_bind($proc, "RETVAL", &$return, SQLINT2);
However, I can't figure out how to access the return value in PDO; I'd prefer not to use an OUT parameter, as alot of these Stored Procedures have already been written. Here is an example of how I am currently calling the procedure in PHP.
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, 'mystr', PDO::PARAM_STR);
$stmt->bindParam(2, 'mystr2', PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Check out MSDN for info on how to correctly bind to this type of call
Your PHP code should probably be tweaked to look more like this. This may only work if you're calling through ODBC, which is honestly the strongly preferred way to do anything with SQL Server; use the SQL Native Client on Windows systems, and use the FreeTDS ODBC driver on *nix systems:
<?php
$stmt = $this->db->prepare("{?= CALL usp_myproc}");
$stmt->bindParam(1, $retval, PDO::PARAM_STR, 32);
$rs = $stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "The return value is $retval\n";
?>
The key thing here is that the return value can be bound as an OUT parameter, without having to restructure the stored procedures.
Just had this same problem:
<?php
function exec_sproc($sproc, $in_params)
{
global $database;
$stmnt = $database->prepare("EXEC " . $sproc);
if($stmnt->execute($in_params))
{
if($row = $stmnt->fetch())
{
return $row[0];
}
}
return -1;
}
?>
can't u use SELECT to return the results?
Then you can use a dataset (resultset in php?) to pick it up?
I don't know know PHP, but in c# its quite simple - use a dataset.
pretty sure PDO::exec only returns number of rows.. this would be $rs in your example
If I understand your question properly you shouldn't have to call fetchAll()...
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, $mystr, PDO::PARAM_STR);
$stmt->bindParam(2, $mystr2, PDO::PARAM_STR);
$rs = $stmt->execute();
echo "The return values are: $mystr , and: $mystr2";
PDOStatement::bindParam
public function callProcedure($sp_name = null, $sp_args = []) {
try {
for($i = 0; $i < count($sp_args); $i++) {
$o[] = '?';
}
$args = implode(',', $o);
$sth = $connection->prepare("CALL $sp_name($args)");
for($i = 0, $z =1; $i < count($sp_args); $i++, $z++) {
$sth->bindParam($z, $sp_args[$i], \PDO::PARAM_STR|\PDO::PARAM_INPUT_OUTPUT, 2000);
}
if($sth->execute()) {
return $sp_args;
}
} catch (PDOException $e) {
this->error[] = $e->getMessage();
}
}
I had a similar problem and was able to solve it by returning the execute like so...
function my_function(){
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, 'mystr', PDO::PARAM_STR);
$stmt->bindParam(2, 'mystr2', PDO::PARAM_STR);
return $stmt->execute();
}
All that is left is to call the function using a variable and then analyse said variable.
$result = my_function();
You can now analyse the contents of $result to find the information you're looking for. Please let me know if this helps!
Try $return_value

Categories