mysqli inserts typed values but not variables - variables

I have tried to get the following code to work. It is an ajax-call where I send a json-encoded string 'data':
<?php
require_once('connect.php'); // get values for mysqli-connect
$arr1 = json_decode($_GET['data']);
$arr = array_values($arr1);
if ($GLOBALS['TSFE']->loginUser) {
$mysqli = new mysqli($server,$user,$pw,$db);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//values to be inserted in database table
$var1 = "Hello World";
$var2 = 45;
$var3 = "an encoded array";
/*
$var1 = $arr[1];
$var2 = $arr[2];
$var3 = json_encode($arr[3]);
*/
$insert_row = $mysqli->query("INSERT INTO table_testing
(event, pid, myarray) VALUES ('$var1', '$var2', '$var3')");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
} else {
echo "User is NOT logged in!\n";
}
?>
My problem is that this code works! It works fine with the three values that are stored in $var1-3. They are saved in the correct table.
But - if I try to store the out-commented three values from $arr[1-3] into $var[1-3] it doesn't work? The three values saved are ' ' (empty), '0' and 'NULL'.
I have tried to put these lines in right after $arr is declared:
echo $arr[1]."\n";
echo $arr[2]."\n";
echo json_encode($arr[3])."\n";
In the console the correct values are printed, so they are valid and exist. It is a string, an integer and an array.
What is it I have overlooked or not understood?

Indexes of PHP arrays start are 0-based.
Try with this code:
echo $arr[0] . "\n";
echo $arr[1] . "\n";
echo json_encode($arr[2]) . "\n";

Related

edit the dynamic data from repeat region in php

I want to edit a record set based on FileNo, which is linked with another table with fileno as the linking fields. I am here providing the two set of codes, one is working and other is giving the code error.
Working code:
$sql="SELECT * FROM casedt WHERE AdvUser= '".$_SESSION['MM_Username']."' && FileNo = $fileno ";
$result= mysqli_query($link, $sql) or die ('Unable to run query:'.mysql_error());
#$count=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
echo "<table border='1'><tr><th>Adv User</th><th>File No.</th><th>Next Dt</th><th>Comments</th><th></th></tr>";
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>".$row["AdvUser"]."</td><td>".$row["FileNo"]."</td><td>".$row["NextDt"]."</td><td>".$row["Comments"]."</td></tr>";
}
Non-working code:
$sql="SELECT * FROM casedt WHERE AdvUser= '".$_SESSION['MM_Username']."' && FileNo = $fileno ";
$result= mysqli_query($link, $sql) or die ('Unable to run query:'.mysql_error());
#$count=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
echo "<table border='1'><tr><th>Adv User</th><th>File No.</th><th>Next Dt</th><th>Comments</th><th></th></tr>";
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>".$row["AdvUser"]."</td><td>".$row["FileNo"]."</td><td>".$row["NextDt"]."</td><td>".$row["Comments"]."</td><td><a href=EditDate.php?recordID= .$row['FileNo'] Edit</a></td</td></tr>";
}

PDO Exception 42000

I have tried to insert data into my database but I keep getting this error that I can't figure out. Been all over the forums and cant find an answer so I thought I would post.
Full error for reference.
error
Code:
<?php
$Records = $connect->query('SELECT COUNT(ID) as counted FROM listings;');
$fetchdata = $Records->fetch();
$i = $fetchdata['counted'];
$i++;
$name = 'hold';
$OS = 0;
if(isset($_POST['name'])){
$name = $_POST['name'];
$type = $_POST['type'];
$loc = $_POST['loc'];
$desc = $_POST['desc'];
$prem = $_POST['premium'];
}
if($name != 'hold'){
$sql = "INSERT INTO listings (name,premium,location,type,desc,onsite,ID,paymentid) VALUES (:Name,:Prem,:Loc,:Type,:Desc,:Onsite,:ID,:Paymentid);";
$Appquery = $connect->prepare($sql);
$Appquery->bindParam(':Name', $name, \PDO::PARAM_STR);
$Appquery->bindParam(':Prem', $prem, \PDO::PARAM_INT);
$Appquery->bindParam(':Loc', $loc, \PDO::PARAM_STR);
$Appquery->bindParam(':Type', $type, \PDO::PARAM_STR);
$Appquery->bindParam(':Desc', $desc, \PDO::PARAM_STR);
$Appquery->bindParam(':Onsite', $OS, \PDO::PARAM_INT);
$Appquery->bindParam(':ID', $i, \PDO::PARAM_INT);
$Appquery->bindParam(':Paymentid', $i, \PDO::PARAM_INT);
$Appquery->execute();
header("Location: index.php");
}
?>
Both desc and type are reserved MySQL keywords. Just quote them as:
$sql = "INSERT INTO listings (name,premium,location,`type`,`desc`,onsite,ID,paymentid) VALUES (:Name,:Prem,:Loc,:Type,:Desc,:Onsite,:ID,:Paymentid);";
// ^ ^ ^ ^

How can I use sql data in header link?

I need to use a variable from SQL. I can print which I wrote the variable. But I can't use
it when it out of while query.
Here is the SQL:
if ($result = $mysqli->query("SELECT * FROM organize WHERE organize.nid=$nid"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
echo $row->nid;
echo $row->omid;
$id=$row->omid;
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
And the header under this scripts.
header("Refresh: 10;http://localhost/records.php?mid= $id ");
I know this is not right way. But I show you what I want. Need to use that 'omid' in header inseat of '$id'.
Finally I resolved it. This scripts like the above codes. I didn't understand why It didn't work. Maybe because I should not use
echo $row->nid;
echo $row->omid;
or
$id=$row->omid;
The right usage is as follows:
while ($row = $result->fetch_object())
{
$dd=$row->omid;
}
header("Refresh: 2;http://localhost/records.php?mid= $dd");

Does Laravel Input::hasfile() work on input arrays?

I'm working on a Laravel project that uses a form with multiple file inputs. If I submit the form with the first input empty and all other inputs with a file, then hasFile returns false. It will only return true if the first input contains a file.
if(Input::hasfile('file'))
{
// do something
}
This is the input array via Input::file('file). The small image input is empty, but the large is not. I'd like it to look at the whole array and if there any files present, then proceed with the "do something".
Array
(
[small] =>
[large] => Symfony\Component\HttpFoundation\File\UploadedFile Object
(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image_name.jpg
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/jpeg
[size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 44333
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[pathName:SplFileInfo:private] => /Applications/MAMP/tmp/php/phpHILgX2
[fileName:SplFileInfo:private] => phpHILgX2
)
)
Is this expected behavior? Or, should it be looking at the entire array?
You can check by using the array key for example like below :-
HTML Input type File Element :
<input type="file" name="your_file_name[]" />
Laravel 5 : $request->hasFile('your_file_name.'.$key)
Laravel 4.2 : Input::hasFile('your_file_name.'.$key)
Taken from source:
/**
* Determine if the uploaded data contains a file.
*
* #param string $key
* #return bool
*/
public function hasFile($key)
{
if (is_array($file = $this->file($key))) $file = head($file);
return $file instanceof \SplFileInfo;
}
It seems that it only checks the first one from the array, head returns the first item from the array.
Since I can't comment, seems I'll have to post.
Ronak Shah's answer really should be marked the correct one here, and when I figured out why, it instantly had me saying "Sonnofa--" after 30-40 minutes trying to figure this... "mess" out.
Turns out to use hasFile() on an input array, you need to use dot notation.
So (using my own example) instead of
$request->hasFile("img[29][file]")
it needs to be
$request->hasFile("img.29.file")
That's certainly an eye-opener, given that PHP and dot notation don't really go together. Input arrays really are problem children.
here is a snippet that may help
if(Input::hasFile('myfile')){
$file = Input::file('myfile');
// multiple files submitted
if(is_array($file))
{
foreach($file as $part) {
$filename = $part->getClientOriginalName();
$part->move($destinationPath, $filename);
}
}
else //single file
{
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('myfile')->move($destinationPath, $filename);
}
} else {
echo 'Error: no file submitted.';
}
Taken from
http://forumsarchive.laravel.io/viewtopic.php?id=13291
At the time of writing (Laravel 8) the Request class now supports arrays for the hasFile method, as from the source code:
/**
* Determine if the request contains the given file.
*
* #param string $name
* #param string|null $value
* #param string|null $filename
* #return bool
*/
public function hasFile($name, $value = null, $filename = null)
{
if (! $this->isMultipart()) {
return false;
}
return collect($this->data)->reject(function ($file) use ($name, $value, $filename) {
return $file['name'] != $name ||
($value && $file['contents'] != $value) ||
($filename && $file['filename'] != $filename);
})->count() > 0;
}

Accessing Associative Indexes Produced by PDO FETCH_ASSOC

I fully admit must have a faulty understanding of the construction of an associative array.
The following login script will populate $userdata with an associative array consisting of $username's hashed password and salt as queried from the SQL Server database (Azure SQL to be specific). However, the portions of the code that are working on creating a hash of the supplied password and comparing against the hashed password found in the DB fail with errors indicating that $userdata[password] and $userdata[salt] are undefined.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $databasestringname", "$usernamestringname", "$passwordstringname");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, );
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
//Query database for the hashed password and salt for the supplied username
if(!empty($_POST)) {
try
{
$sql_select = $conn->prepare("SELECT password, salt FROM logins WHERE username = '$username'");
$sql_select->execute();
}
catch(Exception $e)
{
die(var_dump($e));
}
//Fetch all of the remaining rows in the result set
$userdata = $sql_select->fetchAll(PDO::FETCH_ASSOC);
//check for a valid username
if(empty($userdata))
{
echo "User: $username was not found";
die;
}
//hash the queried salt and hash the supplied password
$hash = hash('sha256', $userdata['salt'] . hash('sha256', $password) );
//compare the hashed salted password supplied with that queried from database
if($hash = $userdata['password'])
{
echo "Welcome, $username!";
}
else
{
echo "Invalid password";
}
}
?>
While I don't doubt some of the code beyond fetching the array from $sql_select needs some debugging I can't get that far because $userdata appears to get all of the associative array data assigned to a single portion of the variable as indicated by the output of the following dumps:
var_dump($sql_select);
//output = object(PDOStatement)#2 (1) { ["queryString"]=> string(61) "SELECT password, salt FROM logins WHERE username = 'mrtactics'" }
list($a[0], $b[1]) = $userdata;
var_dump($a);
var_dump($b);
//output = array(1) { [0]=> array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" } } array(1) { [1]=> NULL }
var_dump($userdata["salt"]);
//output = NULL
var_dump($userdata['salt']);
//output = NULL
var_dump($userdata['password']);
//output = NULL
foreach ($userdata as $item => $value)
echo "$item: $value<br>";
//output = 0: Array
$password = $sql_select->fetchColumn(0);
$salt = $sql_select->fetchColumn(1);
var_dump($password);
var_dump($salt);
//output = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" bool(false)
The obvious workaround is to query a single value for the supplied username and pass each tot heir respective variables. However, this requires twice the necessary calls to the DB and I don't learn anything about how associative arrays are constructed and how I can get use the information stored within them.
I suspect I'm either fetching an object of the wrong construction for the method I am trying to retrieve from it or my syntax is just plain bad. I do intend to remain using PDO as opposed to sql_* commands.
EDIT: Let's make this more simple, then:
$userdatasql = $sql_select->fetchAll(PDO::FETCH_ASSOC);
$userdata['password']="f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a";
$userdata['salt']="6e0";
var_dump($userdata);
var_dump($userdatasql);
var_dump($userdata['password']);
var_dump($userdatasql['password']);
//Dump of $userdata = array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" }
//Dump of $userdatasql = array(1) { [0]=> array(2) { ["password"]=> string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a" ["salt"]=> string(3) "6e0" } }
Note the difference in the construction of these 2 arrays? I don't know exactly what it means which is why I'm here. If I were guessing it appears that the $userdatasql array contains an array within an array so calls must be indexed as such.
//Dump of $userdata['password'] = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a"
//Dump of $userdatasql['password'] = NULL
MORE INFO:
echo (count($userdata));
echo (count($userdatasql));
//output = 2
//output = 1
echo (count($userdata, 1));
echo (count($userdatasql, 1));
//output = 2
//output = 3
This tells me that the array created by PDO FETCH_ASSOC is of a different construction than an array manually created but containing the same 2 pieces of data and the same 2 indexes.
Armed with this knowledge I modified my dump to include the 0 index location and suddenly the expected data was being output:
var_dump($userdatasql['0']['password']);
var_dump($userdatasql['0']['salt']);
//password dump = string(64) "f24704c0ce72a618cf1738894ebdd6001f4d3329802ab83bd418df66cbc46b1a"
//salt dump = string(3) "6e0"
Does this mean that I must reference all PDO FETCH ASSOC arrays by index?
I should think not since no code examples I find show this.
So, then, why is my PDO FETCH ASSOC array malformed?
Well, I have the "answer" in the sense that I can format the syntax to retrieve the necessary information from the associative array. I do not understand the difference between a manually created associative array and one created by PDO FETCH ASSOC nor what the implications are going to be later on when my arrays are significantly more complex than the one posed here.
But, here's the "answer":
The information stored in the associative array created by PDO FETCH ASSOC must be referenced by the numerical index THEN the associative index despite being an associative array not of the numerical type (because that makes loads of sense, right?) By including the numerical index prior to the associative index the value was correctly obtained.
$var[0][index] //retrieves correctly
$var[index] //does not unless the array happened to be manually constructed
And the final, for real answer, deduced after hours of studying other relevant code examples:
My code is performing as it is because I am using ->fetchAll as opposed to ->fetch. When I use simply ->fetch I no longer have to reference both numerical and associative indexes and can simply reference the associative index as expected for an associative array.
The corrected code syntax follows:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to SQL Server
include '../../phpconfig/connectstrings.php';
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $databasestringname", "$usernamestringname", "$passwordstringname");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
catch(Exception $e)
{
die(var_dump($e));
}
//Query database for the hashed password and the salt for the supplied username
if(!empty($_POST)) {
try
{
$sql_select = "SELECT password, salt FROM logins WHERE username = ?";
$stmt = $conn->prepare($sql_select);
$stmt->bindValue(1, $username);
$stmt->execute();
}
catch(Exception $e)
{
die(var_dump($e));
}
//Fetch the result set into an associative array
$userdata = $stmt->fetch(PDO::FETCH_ASSOC);
if(empty($userdata))
{
echo "User: $username was not found";
die;
}
//hash the queried salt with a hash of the supplied password
$hash = hash('sha256', $userdata['salt'].hash('sha256', $password));
//compare the hashed salted password supplied with that queried from database
if($hash == $userdata['password'])
{
echo "Welcome, $username!";
}
else
{
echo "Invalid password";
//does the user wish to register> -> header('Location: register.php');
die;
}
}
?>