Joining a string and array elements not working - php

Here is my PHP code:
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$statecodes = array(0=>"test1","test2");
while($i<sizeof($statecodes)) {
$ini = "users_";
$var = sprintf("%s%s", $ini, $statecodes[$i]);
print $var;
$query = "CREATE DATABASE IF NOT EXISTS" . $var;
$stmt = $mysqli->prepare($query);
/* Execute the statement */
$stmt->execute();
$i=$i+1;
/* close statement */
$stmt->close();
}
And the output i get is
users_
I want to create databases named user_test1 and user_test2

Try this out. You were missing a space after IF NOT EXISTS and your loop was broken due to not initializing your counter. PHP provides a lot of convenient methods for doing things like array traversal and string concatenation; looking at your code I'd guess your experience is with a much lower level language? Things like printf() come in handy for some tasks, but it's overkill when you just want to jam two strings together!
Finally, no need to prepare and execute a query if it isn't a prepared statement with placeholders. You will, however, want to sanitize your input and check the result of your query for errors.
<?php
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$statecodes = array("test1","test2");
foreach ($statecodes as $state) {
$var = "users_$state";
// remove dangerous characters!
$var = preg_replace("/[^\w]/", "", $var);
$query = "CREATE DATABASE IF NOT EXISTS $var";
$result = $conn->query($query);
if (!$result) {
//do something!
}
}

Related

Using MYSQLI in seperate / distinct PHP functions

I'm transitioning from MYSQL to MYSQLI and I am in need of assistance with putting MYSQLI into separate / distinct functions.
From all the "tutorials" i have located on the web, they all have everyrything in one big long code, and not distinct / separate functions that my main scripts can call.
Eg :-
Connect to MYSQLI
Do SELECT
Exit MYSQLI
what i'm after is :-
MYSQLI.PHP
<?
function connect_mysqli()
{
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno();
}
// Return the connection back to where i called it ??
}
function do_query ($sql)
{
$row = $con->query("$sql")->fetch_array();
return $row;
}
function close_mysqli()
{
$mysqli->close();
}
?>
in my script i want to call :-
another.php
<?
include_once("MYSQLI.PHP");
connect_mysqli();
....
do some SELECT
do some UPDATE
close_mysqli();
?>
So far, from the error codes I am receiving, the "connection" to mysqli is not being passed to/from my other script(s)
Has anyone got a working / tested example of mysqli using functions (not just half the code) - but a working example of simple SELECT
Once i get that far, i can do the rest.
fix your include file to
/**
* #return mysqli
*/
function connect_mysqli()
{
$con = mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno());
}
return $con;
}
function do_query ($con, $sql)
{
$row = $con->query("$sql");
if($row) {
return $row->fetch_array();
}
return null;
}
function close_mysqli($con)
{
$con->close();
}
now you can run a script like this
include_once("MYSQLI.PHP");
$connection = connect_mysqli();
if(null !== $connection) {
print_r(do_query($connection, "SELECT * FROM yourTable"));
close_mysqli($connection);
}
but for correct handling create a connection interface and a implementation for mysqli like this
interface myConnectionClass {
function connect();
....
}
and a mysqli implementation
class myMysqlIConnection implements myConnectionClass {
function connect() {
//do more... save connection etc...
return true; //sucess
}
}
Example Demos
Scroll down there are a lot of exmaples...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>

PHP - prepared statements and json_encode

I want to create a php script using prepared statements to query a table in my database and return the results in json format. I have a table of doctors and i want to return the doctors of a given speciality. I have a version of the script that doesn't use prepared statements that works fine. But when i use prepared statements my script doesn't work.
Non - prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality='$speciality'";
$result = $mysqli->query($query) or die("Error executing the query");
while($row = $result->fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$mysqli->close();
?>
prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality=?";
if ($stmt = $mysqli -> prepare($query)){
$stmt -> bind_param("s", $speciality);
$stmt -> execute();
$result = $stmt -> get_result();
while($row = $result -> fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$stmt -> close();
} else {
echo $mysqli->error;
echo "no entry found";
}
$mysqli->close();
?>
What am i doing wrong? I don't get a mysqli error which means that the problem is after the execution of the query but i just don't know what it is.
Edit: What i mean by saying it doens't work is that i don't get anything back. The html body of the page after the execution is completely empty. On the other hand if i use the other script i posted (without prepared statements) i get the expected result.
UPDATED:
Use this:
/* bind result variables */
$stmt->bind_result($col1,$col2,$col3,$col4);
/* fetch values */
while ($stmt->fetch()) {
$output[]=array($col1,$col2,$col3,$col4);
}
Instead. Hope it helps.
anyone please give reason of putting downvote.
ini_set('display_errors',1);
error_reporting(E_ALL);
and then look at HTML body again. Most likely get_result is not supported but I hate to guess.
Make sure your version of PHP is compatible with the method
http://php.net/manual/pt_BR/mysqli-stmt.get-result.php
To get data as associative array you can do as follow:
$stmt->bind_result($col1, $col2);
$rows = [];
while ($stmt->fetch()) {
$rows[]=array("col1"=>$col1, "col2"=>$col2);
}

PHP-Linking forms Using ID

I have a database in which I have a main form that list all personnel using this code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("datatest", $con);
$result = mysql_query("SELECT * FROM Personnel");
echo "<TABLE BORDER=2>";
echo"<TR><TD><B>Name</B><TD><B>Number</B><TD><B>View</B><TD></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["Surname"]." ".$myrow["First Names"]."<TD>".$myrow["Number"];
echo "<TD>View";
}
echo "</TABLE>";
?>
</HTML>
As you can note I have a link to view details of the person but when I click on the VIEW link I get the following error
Parse error: syntax error, unexpected 'EmployeeID' (T_STRING) in C:\Program Files\EasyPHP-12.1\www\my portable files\dss4\childdetails.php on line 6
The childdetails.php has the following code
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children;
WHERE "EmployeeID="["$EmployeeID"],$db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>
Since the first form to list the personnel works I believe the problem is in childdetails.php on line 6 as returned by the server but I simply don’t know how to fix it.
Note: a person can have more than one child as well as having more than one wife
Help please
I would say more like.
$result = mysql_query("SELECT * FROM children WHERE EmployeeID='$EmployeeID'");
// as far $EmployeeID is actualy set before running a query
//but as comment says don't use mysql better something like this
<?php
$mysqli = new mysqli('localhost', 'root', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM children WHERE EmployeeID=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $EmployeeID);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($Employee);
/* fetch value */
$stmt->fetch();
printf($Employee);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
To begin with, your query is wrong, you're telling the sql that your script is over and that it should start executing something new. I'll show you how to do it properly here below.
Also, don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Also, learn to use prepared statements to avoid sql injection, you want the variables to be used as strings into a prepared query, not as a possible executing script for your sql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM children WHERE EmployeeID = :employeeID;"; // Construct the query, making it accept a prepared variable.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':employeeID' => $EmployeeID)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$ChildName = $row['ChildName'];
$Mother = $row['Mother'];
$DateOfBirth = $row['DateOfBirth'];
echo "Child Name: $ChildName";
echo "<br />Mother: $Mother";
echo "<br />Date of Birth: $DateOfBirth";
}
You should use a similar approach to receive $EmployeeID but this should help you a lot.
By the way: remember to close your break tags with a whitespace ' ' and a forwardslash like I showed you.
You
Need
change your query something like this
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children WHERE EmployeeID=" . $EmployeeID, $db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>

Example php code for connecting and getting a sql stored proceedure

Can any one give
The Example php code for connecting and getting a sql stored proceedure
what do you prefer to use? Here is an example taken from php.net:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL get_items(1, #param1, #param2); ";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
remember, that you have to free the resultset, if you do not, you will get an error while executing a next query.
Before I know something about mysqli, I apply mysqli to handle sp's. Just take a look at the follwing example:
$rs = mysql_query("CALL get_items(1, #param1, #param2); ");
$rs = mysql_query("SELECT #param1, #param2" );
while($row = mysql_fetch_assoc($rs))
{
print_r($row);
}
Calling a Stored procedure with PDO

having trouble with getting rows back from msqli::multi_query

I've got an sql query that contains a number of statements. It:
sets a user variable
calls a stored procedure
calls another stored procedure
selects some data
I know that the query is correct, because I've tested it in MySQL Workbench, under the same user. The query is this:
set #current_post = 535; /* 535 for testing, this will be a variable */
call under_user_type(#currrent_post, #user_type, #user_id);
call get_category(#current_post, #category);
select p.post_title, p.post_name,
(
swell_wp.post_score(p.ID)
) as score,
(
swell_wp.is_under_user(p.ID, #user_type, #user_id)
) as under_user,
(
swell_wp.is_under_category(p.ID, #category)
) as under_category
from wp_posts as p
where p.post_type = 'post'
and p.id != #current_post
and p.post_status = 'publish'
having (
under_user = true
or under_category = true
)
order by score desc;
that's just stored in a string: $sql. I then do this with it in PHP:
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query->multi_query($sql);
do {
$query->next_result();
} while( ! $result = $query->use_result() );
print_r($result);
this prints a result object, but one that is empty. Trying to iterate over it doesn't produce any results either.
What am I doing wrong? Can I even use user variables like this? Or will I need to turn the procedures into stored functions and do three separate queries?
Try this:
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($query->multi_query($sql)) {
do {
if ($result = $query->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
} while ($query->next_result());
} else {
echo 'ERROR FOR QUERY!';
}
This should help you trap any errors. Also, I think your use_result needs to be swapped with the next_result.
UPDATED: One other thing, have you checks to make sure the variables you are passing to the query actually contain data? Print our the query to make sure you can run it in the database and get results manually too.
You are apparently not fetching the rows from the result. Please change the code to this and it will print the results.
$query = new MySQLi(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query->multi_query($sql);
do {
/* store first result set */
if ($result = $query->use_result())
{
while ($row = $result->fetch_row())
{
print_r($row);
}
$result->close();
}
/* print divider */
if ($query->more_results())
{
printf("-----------------\n");
}
} while ($query->next_result());

Categories