How to compare PHP variable to value from PHP array - php

I am trying to execute an SQL query to pull one column of data from my database into a PHP array, and then search for my session variable in that array. I've printed the contents of my array and it looks like the query is working and is filling the array, but my comparison if (in_array("$session", $result)) is not working correctly.
I know the string my session variable contains is inside the PHP array. But $execute never flips to FALSE. Any idea why?
$confirm = $_GET['name'];
$execute = TRUE;
session_start();
$session = $_SESSION['sessionID'];
$result = array();
try{
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(substr($session, 0, 2) === 'DS'){
$sql = $conn->prepare("SELECT confirmNum FROM `DSattendance`");
$sql->execute();
$result = $sql->fetchAll();
}
else if (substr($session, 0, 2) === 'BYOD'){
$sql = $conn->prepare("SELECT confirmNum FROM BYODattendance");
$sql->execute();
$result = $sql->fetchAll();
}
}
catch(PDOException $e){echo $sql . "<br>" . $e->getMessage();}
if (in_array("$session", $result)) {
echo "true";
$execute = FALSE;
}
if ($execute == FALSE)
echo "ALREADY REGISTERED";
var_dump($result) yields:
array(10) {
[0]=> array(2) { ["confirmNum"]=> string(11) "adfafafafaa" [0]=> string(11) "adfafafafaa" }
[1]=> array(2) { ["confirmNum"]=> string(11) "adsfafafaff" [0]=> string(11) "adsfafafaff" }
[2]=> array(2) { ["confirmNum"]=> string(11) "asdfafafafa" [0]=> string(11) "asdfafafafa" }
[3]=> array(2) { ["confirmNum"]=> string(11) "christrader" [0]=> string(11) "christrader" }
[4]=> array(2) { ["confirmNum"]=> string(11) "christradfe" [0]=> string(11) "christradfe" }
[5]=> array(2) { ["confirmNum"]=> string(11) "sadfadfafaf" [0]=> string(11) "sadfadfafaf" }
[6]=> array(2) { ["confirmNum"]=> string(11) "sadfsfafaaf" [0]=> string(11) "sadfsfafaaf" }
[7]=> array(2) { ["confirmNum"]=> string(11) "sdfsafsadfa" [0]=> string(11) "sdfsafsadfa" }
[8]=> array(2) { ["confirmNum"]=> string(11) "trraafafafa" [0]=> string(11) "trraafafafa" }
[9]=> array(2) { ["confirmNum"]=> string(11) "wesdfdfasfa" [0]=> string(11) "wesdfdfasfa" } }

The PDO Statement fetchAll is returning a multi-dimensional array of the results found in the database. You need to loop through them first and format a new array that you can use to check your session against.
foreach($result as $value) {
$array[] = $value['confirmNum'];
}
if( in_array($session, $array)) {
// your code here
}
As noted by #mr12086, depending on the version of PHP you are using, you can avoid the foreach loop by using: $result = array_column('confirmNum', $result); instead. However, this does require PHP 5.5.0 or higher.

Related

Insert PHP Regex Exploded Array Into MySQL Table

I have an array that I exploded by Regex, here is a part of the array named $data;
array(6) {
[0]=>
array(1) {
[0]=>
string(77) "Achnanthes brevipes C.Agardh, Syst. Alg.: 1 (1824). / Küçük sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(8) "brevipes"
}
[3]=>
array(1) {
[0]=>
string(8) "C.Agardh"
}
[4]=>
array(1) {
[0]=>
string(21) "Syst. Alg.: 1 (1824)."
}
[5]=>
array(1) {
[0]=>
string(22) "Küçük sucıncığı"
}
}
array(6) {
[0]=>
array(1) {
[0]=>
string(89) "Achnanthes cocconeiformis Mann, U.S. Nat. Mus., Bull. 6: 182 (1925). / Top sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(14) "cocconeiformis"
}
[3]=>
array(1) {
[0]=>
string(4) "Mann"
}
[4]=>
array(1) {
[0]=>
string(36) "U.S. Nat. Mus., Bull. 6: 182 (1925)."
}
[5]=>
array(1) {
[0]=>
string(17) "Top sucıncığı"
}
}
array(6) {
[0]=>
array(1) {
[0]=>
string(108) "Achnanthes gibberula Grunow, Kongl. Svenska Vetensk.-Akad. Handl. 17(2): 121 (1880). / Kambur sucıncığı."
}
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
}
[2]=>
array(1) {
[0]=>
string(9) "gibberula"
}
[3]=>
array(1) {
[0]=>
string(6) "Grunow"
}
[4]=>
array(1) {
[0]=>
string(55) "Kongl. Svenska Vetensk.-Akad. Handl. 17(2): 121 (1880)."
}
[5]=>
array(1) {
[0]=>
string(20) "Kambur sucıncığı"
}
}
and many more..
my regex is:
$turRegex = '/^([^\s]+)[\s]([^\s]+)[\s]([^\s]+)[,][\s]([A-Za-z].+)[\s][\/][\s](.+)[.]/m';
my foreach loop:
foreach ($data as $data) {
if (!empty(preg_match_all($turRegex, $data, $matches))) {
echo "<pre>";
var_dump($matches);
echo "</pre>";
}
}
My table name is "algeaSpecies" and columns are; "id","genusName","speciesEpiteth","author", "publication","TurkishName"
I want to insert this to genusName;
[1]=>
array(1) {
[0]=>
string(10) "Achnanthes"
this to speciesEpiteth;
[2]=>
array(1) {
[0]=>
string(8) "brevipes"
}
and others...
I'm using MySQLi
Thank you
First I noticed you used $data both as array and item in your loop.
In the following code, I assumed that you don't want the first index (the query wasn't clear).
Also, replace the DB connection credentials.
$con = new mysqli('db_host', 'username', 'password', 'db_name');
$boundArray = array_fill(0, 5, null);
$query = "INSERT INTO `algeaSpecies` (`genusName`, `speciesEpiteth`, `author`, `publication`, `TurkishName`) VALUES (?,?,?,?,?);";
$stmt = $con->prepare($query);
$stmt->bind_param("sssss", ...$boundArray);
foreach ($data as $item) {
$i = -1;
foreach ($item as $index) {
if ($i === -1) {
$i++;
continue;
}
$boundArray[$i++] = $index[0];
}
$stmt->execute();
}
$stmt->close();
$con->close();

Spliting Single Column Query values to different php variables

need some help with splitting mysql single column query array into different php variables here.
example:
here's the query, it's pretty simple to be honest.
but, i'm running out of ideas right now.
$string = "select Description from tblQuestion
where Employeeid = '$param'"
$query = $this->db->query($string);
$result = return $query->result_array();
btw, i am using Codeigniter and i tried to var_dump and the results are like this.
array(9) { [0]=> array(1) { ["Description"]=> string(5) "tidak" } [1]=> array(1) { ["Description"]=> string(5) "tidak" } [2]=> array(1) { ["Description"]=> string(5) "tidak" } [3]=> array(1) { ["Description"]=> string(5) "tidak" } [4]=> array(1) { ["Description"]=> string(5) "tidak" } [5]=> array(1) { ["Description"]=> string(5) "tidak" } [6]=> array(1) { ["Description"]=> string(5) "tidak" } [7]=> array(1) { ["Description"]=> string(5) "tidak" } [8]=> array(1) { ["Description"]=> string(5) "tidak" } }
i tried to use json_encode and the result is
[{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"},{"Description":"tidak"}]
the question is.
how do i convert this stack of arrays into different variables like this?
$var0 = "tidak";
$var1 = "tidak";
$var2 = "tidak";
$var3 = "tidak";
and on and on....
thanks in advance.
cheers!
Put the results in a foreach loop and assign the values to a dynamic variable...
sample code like,
foreach($results as $key=>$val){
$str = 'var'.$key;
$$str = $val['Description'];
}
echo $var0;

PHP - array_push is replacing instead of add to SESSION Variable

<?php
session_start();
$pid = $_GET['pid'];
$ptype = $_GET['ptype'];
$_SESSION = array();
$_SESSION['cart_items'] = array();
if (isset($_GET['add_cart']) && !empty($_GET['add_cart'])) {
// Add new data to Session var
$newdata = array($pid , $ptype, 1 );
array_push($_SESSION['cart_items'], $newdata);
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
?>
array_push replaces the data already in the $_SESSION with $newdata variable in the $_SESSION instead of adding it.
For example:
I enter the url: ?pid=1&ptype=CH-&add_cart=Add+to+Cart
And the array looks like this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
}
}
That's great. But when I enter another url like: ?pid=1&ptype=CPU-&add_cart=Add+to+Cart
The array looks like this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
instead of this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
[1]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
It replaces the data that was already in the Session. I want it to add to it. How do I do so?
Thanks in advance!
change lines 5&6 from
$_SESSION = array();
$_SESSION['cart_items'] = array();
to
// $_SESSION = array();
// $_SESSION['cart_items'] = array();
array_push wasn't clearing your data. those two lines were clearing your session data on every page load.

PHP PDO access database with wrong username

I'm writing an application using PHP, to test database connection using PDO and just querying "SHOW DATABASES".
However if I try to connect to database with an unexisting user I get connection as well...
for example if I try this, with the correct user (root):
$conn = new PDO('mysql:host=localhost', 'root', '');
$result = $conn->query("SHOW DATABASES");
while($row = $result->fetchAll()){
var_dump($row);
}
and echo the result I get this:
array(5) { [0]=> array(2) { ["Database"]=> string(18) "information_schema" [0]=> string(18) "information_schema" } [1]=> array(2) { ["Database"]=> string(5) "mysql" [0]=> string(5) "mysql" } [2]=> array(2) { ["Database"]=> string(18) "performance_schema" [0]=> string(18) "performance_schema" } [3]=> array(2) { ["Database"]=> string(10) "phpmyadmin" [0]=> string(10) "phpmyadmin" } [4]=> array(2) { ["Database"]=> string(4) "test" [0]=> string(4) "test" } }
however if I use a random string for the username, like this:
$conn = new PDO('mysql:host=localhost', 'sdghasdgas', '');
$result = $conn->query("SHOW DATABASES");
while($row = $result->fetchAll()){
var_dump($row);
}
I still get results but only this:
array(2) { [0]=> array(2) { ["Database"]=> string(18) "information_schema" [0]=> string(18) "information_schema" } [1]=> array(2) { ["Database"]=> string(4) "test" [0]=> string(4) "test" } }
Thanks for the help.

Add Array Column to Multidimensional Array Using array_merge in foreach Loop

I'm trying to add another column of data to each row in a foreach loop. It's purpose is to remember the element of data importeded from XML processed to an multidimensional array. It's stuck as a scalar though the var_dumps looks fine.
<?php
$KEY = 0;
foreach ($eventsArray as $keyMe){
$thisKey['KEY'][0] = strval($KEY);
$keyedArray = array_merge($keyMe, $thisKey);
$KEY++;
}
// Prep for multisort
foreach ($keyedArray as $key => $value){
$date[$key] = $value['DATE'];
$title[$key] = $value['TITLE'];
$link[$key] = $value['LINK'];
$slide[$key] = $value['SLIDE'];
$location[$key] = $value['LOCATION'];
$time[$key]= $value['TIME'];
$KEY[$key] = $value['KEY']; // Warning: Cannot use a scalar value as an array
}
/* var_dump(
array(7) {
["DATE"]=> array(1) { [0]=> string(10) "2012-12-18" }
["TITLE"]=> array(1) { [0]=> string(20) "Event Title" }
["LINK"]=> array(1) { [0]=> string(38) "aLinkLocation.htm" }
["SLIDE"]=> array(1) { [0]=> string(2) "16" }
["LOCATION"]=> array(1) { [0]=> string(8) "Location of Event" }
["TIME"]=> array(1) { [0]=> string(3) "8am" }
["KEY"]=> array(1) { [0]=> string(2) "23" }
}
*/

Categories