mysql - mysqli DB connect scope? -
i'm trying use prepared statements insert data database, within function.
the following works great when called outside file:
function insert($value1, $value2) { $mysqli = new mysqli("localhost", "***", "***", "***"); if (mysqli_connect_errno()) { printf("connect failed: %s\n", mysqli_connect_error()); exit(); } if ($stmt = $mysqli->prepare("insert table (col1, col2) values (?, ?)")) { $stmt->bind_param('ss', $value1, $value2); $stmt->execute(); } }
however want move connect string outside of function, results in scope issues. i've read need class this, can explain example please?
thanks
the easiest thing move connect line outside function (into global scope) , put following inside function @ start:
global $mysqli;
you can use class if , have class variable store connection more involved. again, explained in php documentation examples of creating class, methods & variables , using it.
Comments
Post a Comment