Why displaying array when select column in mysql? - php

I am trying to select a column in mysql in php,
function PageController() {
$data = [
'categories' => _db_get_select("categories", ['name'])
];
load_view("tutu", $data);
and
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$sql = "SELECT name=$columns FROM . $table_name.";
var_dump($sql);
the result is displaying like this
string(42) "SELECT ['name']=Array FROM . categories."
I want to be like this
SELECT name FROM . categories.
Thanks in advance.

You may use this script
function PageController() {
$data = [
'categories' => _db_get_select("categories", "name")
];
load_view("tutu", $data);
And the function will be
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT {$columns} FROM {$table_name}";
}

Just echo your sql variable instead of var dump like below
echo $sql;

Use foreach loop to iterate through an array of columns to form a query.
function PageController() {
$data = array('categories' => _db_get_select("categories", array("name")));
load_view("tutu", $data);
}
And then:
//Start with select
$sql = 'SELECT ';
//Concat column names separated with commas
foreach ($columns as $value) {
$sql .= $value . ', ';
}
//Get rid of the last comma
$sql = rtrim($sql, ', ');
$sql .= ' FROM ' . $table_name;
Check if it's okey:
var_dump($sql);

Related

How to get all values when parameter is null

I have a query form where I need to fetch details from a custom table in MYSQL. If the parameter is left blank all records should be fetched. If there is a value entered in the parameter then records for that value should be fetched.
This is my code so far:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$param_1=mysqli_real_escape_string($conn,$_GET['param_1']);
if (!empty($param_1)){
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1'";
} else {
$sql = 'SELECT column1 ,column2,column3,column4,column5
FROM xxx';
}
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
This works fine with one parameter. I will need to add more parameters and those could also be null.
For e.g.
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1' AND column2='$param_2";
Either of these could be null. How do I take care of this in MYSQL?
My question is what would be the best way to take care of this situation?
Thanks in advance.
You can keep appending the query like this:
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE 1=1 ";
if(!empty($param1)){
$sql.= " and column1='$param1'";
}
if(!empty($param2)){
$sql.= " and column2='$param2'";
}
if(!empty($param3)){
$sql.= " and column3='$param3'";
}
Note: Passing parameters like this would lead to SQL injection, use binding to pass parameters to avoid SQL Injection. Here is a good read about it.
You can follow the below steps
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$whereArr=[];
if(isset($_GET['param_1'])){
$whereArr[]="column1=" . mysqli_real_escape_string($conn,$_GET['param_1']);
}
if(isset($_GET['param_2'])){
$whereArr[]="column2=" . mysqli_real_escape_string($conn,$_GET['param_2']);
}
if(isset($_GET['param_3'])){
$whereArr[]="column3=" . mysqli_real_escape_string($conn,$_GET['param_3']);
}
$whereStr='';
if(count($whereArr)>0){
$whereStr="WHERE " . implode(" AND ",$whereArr);
}
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx " . $whereStr;
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
Check for each param in the above demonstrated, Put them in array.
Then check if array is isset or not, if isset create a where string and the append it to your query.
Even if no param is set your query will run without where clause.
You can do something like this for optimization of your code,
$getArr = array_filter($_GET);
// checking sql injection
$getArr = array_map(function ($v) use ($conn) {
return mysqli_real_escape_string($conn, $v);
}, $getArr);
$temp = [];
// fetching numbers for that key
foreach ($getArr as $key => $value) {
$temp[$key] = preg_replace('/[^\d]/', '', $key);
}
$str = '';
// creating condition for data fetched in get
array_walk($temp, function ($item, $key) use (&$str, $getArr) {
$str .= " column$item = '" . $getArr[$key] . "' AND ";
});
// raw query
$sql = 'SELECT column1 ,column2,column3,column4,column5 FROM xxx';
// if not empty string
if (!empty($str)) {
$sql .= rtrim($str,'AND ');
}
echo $sql;die;

Insert array into db table

I'm trying to learn how to use an array to insert multiple entries into a database table. This was my attempt. What am I doing wrong?
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"1" => array("Jerry Garcia", "193.169.5.11"),
"2" => array("Bill Graham", "193.169.5.12"),
"3" => array("Arlo Guthrie", "193.169.5.13")
);
if(is_array($client) {
$DataArr = array();
foreach($client as $row) {
$fieldVal1 = mysqli_real_escape_string($client[$row][1]);
$fieldVal2 = mysqli_real_escape_string($client[$row][2]);
$fieldVal3 = mysqli_real_escape_string($client[$row][3]);
$DataArr[] = "('fieldVal1', 'fieldVal2', 'fieldVal3')";
}
$sql = "INSERT INTO ip_data (field1, field2, field3) values ";
$sql .= implode(',' , $DataArr);
mysqli_query($conn, $query);
}
I tried this but it still doesn't work. What am I missing?
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("Jerry Garcia"),
"1" => array(""193.169.5.11"),
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$fieldVal1 = mysqli_real_escape_string($client[$row][0]);
$fieldVal2 = mysqli_real_escape_string($client[$row][1]);
$DataArr[] = "('$fieldVal1', '$fieldVal2')";
}
$sql = "INSERT INTO ip_data (field1, field2) values ";
$sql .= implode(',' , $DataArr);
mysqli_query($conn, $query);
}
Thanks for your advice.
Next try.
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("name" => "Peter Maxx", "ip" => "193.169.5.16"),
"1" => array("name" => "Ravi Shankar", "ip" => "193.169.5.17")
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$DataArr[] = "('". mysqli_real_escape_string($conn, $row[0]) ."', '". mysqli_real_escape_string($conn, $row[1]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip)
VALUES
( 'Peter Maxx', '193.169.5.16'),
('Ravi Shankar', '193.169.5.17')";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}
I get these error messages.
PHP Notice: Undefined offset: 0 in php shell code on line 5
PHP Notice: Undefined offset: 1 in php shell code on line 5
PHP Notice: Undefined offset: 0 in php shell code on line 5
PHP Notice: Undefined offset: 1 in php shell code on line 5
It is unclear what your purpose is since the SQL-query in your question specify 3 fields (field1, field2, field3) to be inserted into your table, but you only have 2 values in your clients array. If you want to insert multiple rows in one single query, lets say for the "name" and "ip" value in your clients array, you can do this:
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
//CREATE ARRAY WITH name AND ip VALUES FOR EACH USER...
$DataArr[] = "('". mysqli_real_escape_string($conn, $row[0]) ."', '". mysqli_real_escape_string($conn, $row[1]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip) VALUES ";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}
The $sql variable will contain the following query compliant with the syntax for a multiple insert:
INSERT INTO ip_data (name, ip)
VALUES ('Jerry Garcia', '193.169.5.11'),
('Bill Graham', '193.169.5.12'),
('Arlo Guthrie', '193.169.5.13')
Note that you have $query instead of $slqin your question. It should be: mysqli_query($conn, $sql);.
Another thing: Using mysqli_real_escape_string() the procedural way instead of the object oriented way, as in your example, requires to pass a link identifier to the connection as parameter: mysqli_real_escape_string($conn, $row[0])
UPDATE:
In your latest attempt you have changed the array to an associative array, so this should do it:
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("name" => "Peter Maxx", "ip" => "193.169.5.16"),
"1" => array("name" => "Ravi Shankar", "ip" => "193.169.5.17")
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$DataArr[] = "('". mysqli_real_escape_string($conn, $row["name"]) ."', '". mysqli_real_escape_string($conn, $row["ip"]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip) VALUES ";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}
Please change append to $DataArr[] to this one:
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";
Correct
From
if(is_array($client) {
To
if(is_array($client)){
And your array $client will have only 2 elements in each iteration
From
# You will get PHP Warning: Illegal offset type
# since $row is already array
$fieldVal1 = mysqli_real_escape_string($client[$row][1]);
$fieldVal2 = mysqli_real_escape_string($client[$row][2]);
$fieldVal3 = mysqli_real_escape_string($client[$row][3]);
to
// For first iteration
// $row[0] = "Jerry Garcia"
// $row[1] = "193.169.5.11"
$fieldVal1 = mysqli_real_escape_string($conn, $row[0]);
$fieldVal2 = mysqli_real_escape_string($conn, $row[1]);
// $row[3] does not exists so comment it and set $fieldVal3 some data
// $row[3] not exists in your array and even $row[2]
// or add one value to your $client array and access using $row[2]
// $fieldVal3 = mysqli_real_escape_string($row[3]);
$fieldVal3 ='somedata';
and Finally
From
$DataArr[] = "('fieldVal1', 'fieldVal2', 'fieldVal3')";
To
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";

multi_query() has an error

I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

array values into mysql

I have an array that looks like:
Array ( [0] => 'overview'
[53] => 'PUBLIC'
[54] => '-friendsD'
[55] => 'XHTML'
[56] => '1.0'
[57] => 'Transitional'
[77] => 'People' );
How can I take those values and put them into MySQL with an INSERT? For example INSERT INTO array_value VALUES ('$arrayvalues'). For each array value is a new post into MySQL.
I tried this:
<?php
$homepage = file_get_contents('http://www.mysiteexample.com/');
$array = explode(" ",$homepage);
foreach($array as $val) {
$servername = "localhost";
$username = "111";
$password = "111";
$dbname = "111";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if ($val != " "){
$val = $val. " ";
$query = "INSERT INTO `111` (word) VALUES ('$val')";
$executeQuery = $conn->query($query) === TRUE;
}
if ($executeQuery === TRUE) {
//echo "New record created successfully";
echo $val;
} else {
//echo "Error: " . $query . "<br>" . $conn->error;
echo $val. " ";
}}
$conn->close();
}
?>
This works to some extent. It produces many empty results how could it be filtered to have no empty posts. I tried the $val != " " but this didnt work.
You can loop through the array and build the query. Then execute it.
<?php
$homepage = file_get_contents('http://www.mywebsite.com/');
$array = explode(" ",$homepage);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$executeQuery;
for ($i = 0; $i < count($array); $i++) {
if (!empty($array[$i])) {
$executeQuery = $conn->query("INSERT INTO `yourTable` (yourField) VALUES ('" . $array[$i] . "')");
}
}
if ($executeQuery === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
}
?>

mysql will not insert past fourth row

I'm not exactly sure what happened but this database and the php effecting it were working just fine until it hit the fourth row and now it won't insert new records at all.
if($_POST)
{
$servername = ******;
$username = ******;
$password = ******;
$db = ******;
$conn = mysqli_connect($servername, $username, $password, $db);
mysqli_select_db($conn,$db);
$uuid = $_POST['uuid'];
$sql = "INSERT INTO uuid VALUES ('$uuid');";
mysqli_query($conn,$sql);
mysqli_close($conn);
}
I'm not sure what happened but this is the relevant code for the mysqli query.
try this
<?php
if(isset($_POST['uuid']))
{
$servername = yourServerName;
$username = username;
$password = password;
$dbname = databaseName;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$uuid = $_POST['uuid'];
$sql = "INSERT INTO tableName (columnName) VALUES ('$uuid')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Also, I recommend using prepared statements.

Categories