PHP: Duplicate/Blank values when Inserting image names into the DB - php

I am currently storing in MySQL database image names for easier way to retrieve the actual images. I am having problems with the php code I created that stores the names. Duplicate and blank insertions are being made into the DB without my permission.
Is there a way to avoid this issue of duplicate or blank values being inserted when the page refreshed?
<?
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
if (is_array($images)) {
try {
$objDb = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$objDb->exec('SET CHARACTER SET utf8');
} catch (PDOException $e) {
echo 'There was a problem';
}
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ";
foreach ($images as $image) {
$value[] = "('" . $image . "')"; // collect imagenames
}
$sql .= implode(',', $value) . ";"; //build query
$objDb->query($sql);
}
?>

First, you should be checking for blank names in your foreach statement, as such:
foreach ($images as $image) {
if($image!='') {
$value[] = "('".$image."')"; // collect imagenames
}
}
Secondly, you should look into header("Location: ..."); to prevent users from refreshing the page.
Thirdly, you could also set a session variable or cookie to prevent a user from uploading the same image twice.
Lastly, if the image names are unique, you can set a UNIQUE index on the image name. Then use INSERT IGNORE and that will remove all of your duplicates.

I reformatted things into what I think should be slightly more readable and more easily separate what's going on in the code. I also updated your queries to show how you can properly "sanitize" your input.
I still think the process by which you're going about sending the data to the server is wrong, but hopefully this code helps you out a little bit. I'd also do this more object orientedly.. but I feel that leaves the scope of your question just a little bit =P. It's kind of like everyone else is saying though, the logic for your code was only off just slightly.
As for the duplication thing, look into checking if the file already exists before adding it to the database.
<?php
$_GET['i'] = 'file1.png, file2.png, file3.png'; // This is just for testing ;].
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
//As someone else pointed out, you do not want to use GET for this and instead want to use POST. But my goal here is to clean up your code
//and make it work :].
$images = explode(',', $_GET['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images)//There were no images to return
return false;
$pdo = get_database_connection();
foreach($images as $image)
{
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $pdo->prepare($sql);
$prepared->execute(array($image));
}
}
function get_database_connection()
{
$host = 'localhost';
$db = 'test';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$pdo->exec('SET CHARACTER SET utf8');
} catch(PDOException $e) {
die('There was a problem');
}
return $pdo;
}

The easiest way to avoid duplicates upon refresh is to re-direct the page after the POST, so just doing header("Location: {$_SERVER['PATH_INFO']}"); should solve that for you.
To avoid empty entries try is_array($images) && count($images)

You probably should change the following line:
if(is_array($images)){
to this:
if(!empty($images) && is_array($images)){
explode() returns an empty array even if no "i" parameter is provided

Try setting a session variable and tell it to exit or redirect when session variable is not set.
For example
if (!isset($_SESSION['session_name']))
{
exit();
}

Related

PHP result row as an object not set

I have this PHP code in which I try to edit a row in the database
$sql="SELECT * FROM `event` where `EId`='".$_GET['EId']."'";
$res=$conn->query($sql);
$numrows=mysqli_num_rows($res);
if ($numrows>0)
{
$obj = mysqli_fetch_object($res);
}
if ($_REQUEST["mode"]=="save")
{
if ($_FILES['image']['name']!="")
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
$conn->query($sqlu);
header("refresh:1; url=event_view.php");
die();
}
function post_img($fileName,$tempFile,$targetFolder)
{
if ($fileName!="")
{
if(!(is_dir($targetFolder)))
mkdir($targetFolder);
$counter=0;
$NewFileName=$fileName;
if(file_exists($targetFolder."/".$NewFileName))
{
do
{
$counter=$counter+1;
$NewFileName=$counter."".$fileName;
}
while(file_exists($targetFolder."/".$NewFileName));
}
$NewFileName=str_replace(",","-",$NewFileName);
$NewFileName=str_replace(" ","_",$NewFileName);
copy($tempFile, $targetFolder."/".$NewFileName);
return $NewFileName;
}
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder.$filname))
{
unlink($targetfolder.$filname);
}
}
When this is executed without uploading a new image it removes the present image and saves the row without any image. When uploading a new image it does not delete the current image.
I checked with isset and it tells me that the variable $obj->Picture is not set. I used this code in an older version of PHP and it still works but I can't seem to get it to work in the current one.
I am quite sure that the problem lies with $obj but I can't seem figure out what it is.
The HTML is just a form with file upload input and I have already set up a connection to the database with $conn being a new mysqli. The reason I am taking the entire row is because I am editing other stuff too
It feels like I am committing a fundamental mistake? What am I missing?
I'd bet there is some Problem with the num_rows_function.
Try to structure the code differently or at least make sure you have obj defined and initialised when the part of your code where the object is required is reached.
Do something like this for xample:
if ($_REQUEST["mode"]=="save" && isset($obj))
{
if (($_FILES['image']['name']!=""))
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
(...)
Well, here's how I would fix this up. Your whole logic was messed up; now we have only the two conditions we need: is a valid EId sent, and is a file attached?
Database API is updated to something a tiny bit more modern, queries are prepared and parameterized for security, and we are properly sanitizing user input before using it to name files.
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");
$stmt = $conn->prepare("SELECT Picture FROM event WHERE EId = ?");
$result = $stmt->execute([$_POST["EId"]]);
if ($obj = $stmt->fetch(\PDO::FETCH_OBJ)) {
if (!empty($_FILES["image"])) {
del_img("event/", $obj->Picture);
$Picture = post_img($_FILES['image'], "event");
$stmt = $conn->prepare("UPDATE event SET Picture = ? WHERE EId = ?");
$result = $stmt->execute([$Picture, $_POST["EId"]]);
}
header("Location: event_view.php");
die();
}
function post_img($file, $targetFolder)
{
if (!(is_dir($targetFolder))) {
mkdir($targetFolder);
}
$fileName = $file["name"];
$tempFile = $file["tmp_name"];
$NewFileName = str_replace([",", " "], ["-", "_"], basename($fileName));
$counter = 0;
while(file_exists($targetFolder . "/" . $NewFileName)) {
$counter += 1;
$NewFileName = $counter . $fileName;
}
move_uploaded_file($tempFile, $targetFolder . "/" . $NewFileName);
return $NewFileName;
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder . $filname)) {
unlink($targetfolder.$filname);
}
}

PHP loop the INSERT MySQL for each result

I have already a script which scrapes all the urls of one csv with simple HTML dom.
The output is like this:
CoolerMaster Devastator II Azul
Coolbox DeepTeam - Combo teclado, ratón y alfombrilla
Asus Claymore RED - Teclado gaming
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
As you can see, the scrape contains 3 different products, but when I try to insert to the MySQL database, it only saves the last product --- but three times.
Here you can see my PHP Code for that:
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
$names = $html->find('h1');
foreach ($names as $name) {
echo $name->innertext;
echo '<br>';
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0];
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
So, what I need is the MySQL query add:
INSERT INTO productos (nombre) VALUES('CoolerMaster Devastator II Azul')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Coolbox DeepTeam - Combo teclado, ratón y alfombrilla')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
You have a bunch of problems in your code.
First, you have function scrapUrl, that takes $url as an argument, but doesn't output anyhting. It's setting global $name variable, but, although it's find several names, it putting only the last one to the $name variable, because it's walking through a series of $names, put it's text into $name, and go for the next one, so, only last item is stored to your $name variable.
I would recommend, that your change your scrapUrl function, so it store names of scrapped products into an array, and return that array.
Second, I'm cannot understand how do you put your data into a csv file, the code, you've privided looks like it shouldn't work properly. Are you sure, that you are writing the right data in a csv file? Maybe here you are just reading data from file - in that case, I'm sorry.
The third: you are reading data from csv, and when moving line by line in the cycle, but the data is going nowhere. To my opinion, you should but $linea[0] into your SQL query, but you are putting $name->plaintext where, when $name is set only once in your scrapUrl, as I've mentioned above.
I would recommend, that you use the right variable in your SQL-query to pass data to it.
Also, it's better to use PDO and prepared statements instead of inserting raw data in your string-literals SQL queries.
Here is your code, just formatted: ( please check it you have a missing } )
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name; // -- using global is crap - I would avoid that. Pass the object in as an argument of the function eg. scrapUrl($url, $name)
$names = $html->find('h1');
foreach ($names as $name) {
// -- your re-assigning $name overwriting you global on each iteration of this loop
// -- What is the purpose of this? it does nothing but output?
echo $name->innertext;
echo '<br>';
}
// -- missing } where is this function closed at?
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
// -- this can be combined with the one with the query
// -- just put the function call in that one and delete this one
$url = $linea[0];
scrapUrl($url); //recursive? depends where you function is closed
// -- whats the purpose of this function, it returns nothing?
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- query is vulnerable to SQL injection? prepared statement
// -- whats $name->plaintext? where is it assigned at?
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// -- when you loop over the CSV but insert $name->plaintext multiple times
// -- where is that property changed inside this loop, how is it correlated to the csv data
}
$conn->close();
So first off you are missing a closing } Depending where that should be, depends on what else you have wrong.
One of you loops for the CSV can be eliminated ( maybe ), anyway I put bunch of notes in with comments like this // --
Your main issue, or the reason you inserts are the same is these lines
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- $name->plaintext does not change per iteration of the loop
// -- you are just repeatedly inserting that data
...
See you insert the value of $name->plaintext but this has no correlation to the $csv variable and you are not modifying it. It's no surprise it stays the same.
Ok, now that I picked apart your code ( nothing personal ). Let's see if we can simplify it a bit.
UPDATE This is the best I can do given the above code. I just combined it, fixed some logical errors, trimmed it down and simplified it. It's a common mistake of beginners to over-complicate the task. ( but there is no way for me to test this )
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//prepare query outside of the loops
$stmt = $conn->prepare("INSERT INTO productos (nombre)VALUES(?)");
foreach ($csv as $linea) {
//iterate over each csv line
$html = new simple_html_dom();
//load url $linea[0]
$html->load_file($linea[0]);
//find names in the document, and return them
foreach( $html->find('h1') as $name ){
//iterate over each name and bind elements text to the query
$stmt->bind_param('s', $name->plaintext);
if ($stmt->execute()){
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
There I further simplified it as it doesn't really make sense to have the function scrapUrl(). We're not re-using that code, so it adds a function call and makes the code harder to read by having it.
Even if it doesn't work strait away, I encourage you to compare the original code to what I have. And sort of walk through it in your mind, so you can get an feel for how I removed some of those redundancies etc.
For reference
mysqli prepare: http://php.net/manual/en/mysqli.prepare.php
mysqli bind_param: http://php.net/manual/en/mysqli-stmt.bind-param.php
mysqli execute: http://php.net/manual/en/mysqli-stmt.execute.php
Hope that helps, cheers!
Well, after been thinking about this for quite some time, I've managed to make it work.
I leave the code in case someone else can use it.
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
global $price;
global $manufacturer;
$result = array();
foreach($html->find('h1') as $name){
$result[] = $name->plaintext;
echo $name->plaintext;
echo '<br>';
}
foreach($html->find('h2') as $manufacturer){
$result[] = $manufacturer->plaintext;
echo $manufacturer->plaintext;
echo '<br>';
}
foreach($html->find('.our_price_display') as $price){
$result[] = $price->plaintext;
echo $price->plaintext;
echo '<br>';
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$price_go=str_replace(",",".",str_replace(" €","",$price->plaintext));
$sql = "INSERT INTO productos (nombre, nombreFabricante, precio) VALUES('$name->plaintext', '$manufacturer->plaintext', $price_go)";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Producto añadido al comparador!";
echo '<br>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//echo $url;
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//print_r($csv); // Verás que es un array donde cada elemento es array con una de las url.
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
?>
I'm pretty sure i have some trash in my code, but it works.
I hope it help for someone.
Regards and thanks for all the help.

Inserting form data to a mysql database

I have tried multiple times to get this code to run and insert the data into a my database. No matter what I try I cannot figure out the problem. The php looks like this:
<?php
// Create connection
$conn = mysqli_connect("localhost","nmhsmusi_admin" , "********", "nmhsmusi_musicdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['submit']))
{
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
$run = mysqli_query($conn,"INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES
(
'$titleTag', '$composerTag', '$unicodeTag', '$tempoTag', '$yearTag', '$languageTag', '$keyTag', '$pianoTag', '$temposelTag', '$partsTag'
)");
if ($run) {
echo "New record created successfully";
} else {
echo "failed";
}
mysqli_close($conn);
}
?>
Any help would be greatly appreciated
Why do you use mysqli? Has it already fallen into disuse?
PDO is now used.
Here's an example:
<?php
if (isset($_POST['submit'])) {
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
try {
$pdo = new PDO(DSN,DBUSER,DBUSERPASSWD);
} catch (PDOException $e) {
echo "Failed to connect to Database: " . $e->getMessage() . "\n"; die();
}
$pdo->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
$sql = "INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES (:titleTag,:composerTag,:unicodeTag,:tempoTag,:yearTag,:languageTag,:keyTag,:pianoTag,:temposelTag,:partsTag)";
$query = $pdo->prepare("$sql");
$query->bindValue(':titleTag',$titleTag);
$query->bindValue(':composerTag',$composerTag);
$query->bindValue(':unicodeTag',$unicodeTag);
$query->bindValue(':tempoTag',$tempoTag);
$query->bindValue(':yearTag',$yearTag);
$query->bindValue(':languageTag',$languageTag);
$query->bindValue(':keyTag',$keyTag);
$query->bindValue(':pianoTag',$pianoTag);
$query->bindValue(':temposelTag',$temposelTag);
$query->bindValue(':partsTag',$partsTag);
$query->execute();
if($query->rowCount() > 0){
echo "New record created successfully!";
} else {
echo "Error!";
}
}
?>
Of course you need to filter everything that comes from the form with regular expressions. Easy thing to do!
Once the regular expressions have analyzed everything you need to convert everything to htmlentities to avoid malicious code:
The regular expression "/([a-zÀ-ÿ0-9\s]+)/i" below allows only letters with or without accents, numbers, and spaces:
<?php
preg_match('/([a-zÀ-ÿ0-9\s]+)/i', $_POST['any_field_form'], $output);
if((isset($output[1]) == true) and ($output[1] != null)) {
//Convert everything to htmlentities to avoid malicious code
$get_the_data = htmlentities($output[1], ENT_QUOTES, 'UTF-8', false);
} else {
$get_the_data = null;
}
?>
With this you avoid problems with forms. Of course for each form field you will have to do a specific regular expression. But that makes your code smarter.
Sorry if there are any errors in the text. I know how to read in English, but I do not know how to write so I used a translator for that.
But that's it, boy!

How do I query a database in PHP and return results based on matching user-input?

I’m trying to write a PHP script with MySQLi to query a database.
I’d like it if the user-input could be checked against the database and then return a result from the column ‘conjugation’ if the string in the column ‘root’ of the table ‘normal_verbs’ is in the input.
So if the user input is something like "foobar", and the root-column has "foo", I'd like it to see 'foo' in 'foobar' and return that value of 'conjugation' in that row.
I can’t seem to get the query to work like I want it to. The one I'm using below is basically just a placeholder. I don't entirely understand why it doesn't work.
What I’m trying, is this :
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
if($m === false) {
// Handle failure - log the error, notify administrator, etc.
} else {
// Fetch all the rows in an array
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
print_r ($rows);
It’s not giving me any errors, so I think it’s connecting to the database.
EDIT2: I was wrong. I was missing something obvious due to misunderstanding MySQLi and have edited the code accordingly. So the above code does work in that it connects to the database and returns a result, but I'm still stumped on a viable SQL statement to do what I want it to do.
Please try this:
SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')
It selects all rows where root contains $y anywhere.
In addition, your code is vulnerable to SQL injections. Please look here for more information.
Try this SQL Query Like this
SELECT `conjugation` from normal_verbs where `root` like '%$y%'

Multiple mysql database usage and management in php

My script requires connections to several databases. Some parts only need to connect to one, which is all fine and dandy, however in some cases I need to perform queries on different database in a single script execution.
Currently I'm doing something like this:
function db_connect($which) {
if($which == "main") {
$maindb = mysqli_connect(HOSTNAME_1, USER, PASSWORD, MAIN_DB);
return $maindb;
} elseif($which == "stats") {
$statsdb = mysqli_connect(HOSTNAME_2, USER, PASSWORD, STATS_DB);
return $statsdb;
}
}
$maindb = db_connect("main");
$statsdb = db_connect("stats");
I maintain the actual hostname, username, password and db name in a config file full of constants.
I then use the respective links on different queries.
Is there a cleaner way to do this?
Quite good, although you shoul try not to duplicate your code :
function db_connect($which) {
if($which == "main") {
$host = HOSTNAME_1;
$db = MAIN_DB;
} elseif($which == "stats") {
$host = HOSTNAME_2;
$db = STATS_DB;
} else {
throw new Exception('unknown db');
}
return mysqli_connect($host, USER, PASSWORD, $db);
}
$maindb = db_connect("main");
$statsdb = db_connect("stats");
That seems to be ok. An alternative would be to use the class mysqli instead of the functions in order to manipulate objects instead of identifiers.
You could store your databaseconfigs in arrays and use that. That's how codeigniter does it.
function get_database_config(){
$config['main']['hostname'] = "host1";
$config['main']['user'] = "user1";
$config['main']['password'] = "pass1";
$config['main']['database'] = "database1";
$config['stats']['hostname'] = "host2";
$config['stats']['user'] = "user2";
$config['stats']['password'] = "pass2";
$config['stats']['database'] = "database2";
return $config;
}
function db_connect($db)
{
$config = get_database_config();
return mysqli_connect(
$config[$db]['hostname'],
$config[$db]['user'],
$config[$db]['password'],
$config[$db]['database']
);
}
If you don't want to work with an associative array and prefer to work with constants, you could name your constants as MAIN_HOSTNAME, STATS_HOSTNAME, ... and use constant($which . '_HOSTNAME') as input for mysqli_connect().

Categories