PHP AJAX - Function not Returning SQL ID - javascript

I am trying to get a query to run where it returns the SQL row's id of a user using a collar number through PHP.
For some reason, it is not working and providing an error: trying to access array offset on value of type null. Full Error Message - https://gyazo.com/38367bee5066d16f419a43aab93cbc89
I am not exactly sure how to fix this, I've tried a lot of things. I want the function to return the id so I can then use it where ever needed. I am using PHP's include functions.
UpdatePassword.php
session_start();
include("functions.php");
$id = findUserID(array_key_exists("collar", $_POST));
echo($id);
Functions.php
function findUserID($collar){
$id = "";
include("../connection.php");
$query = "SELECT `id` FROM `users` WHERE collar = '".mysqli_real_escape_string($link, $collar)."'";
if ($result = mysqli_query($link, $query)){
//echo "Query was Successful";
$row = mysqli_fetch_array($result);
return($row['id']);
}
}

Using PHP ternary operator to show one example validating your $_POST input:
$id = ( array_key_exists("collar", $_POST) )
? findUserID($_POST['collar'])
: 0;
That is shorthand for:
if ( true === array_key_exists("collar", $_POST) ) {
$id = findUserID($_POST['collar']);
}
else {
$id = 0;
}
Other validation checks can be included in each method:
$id = (
array_key_exists("collar", $_POST) // key exists
&& "" !== $_POST['collar'] // not empty string
)
? findUserID($_POST['collar'])
: 0; // if not valid, assign default value

Related

HTML collection getting parsed to JavaScript through PHP when it should be a String

I have a database that I use to create a resource of string values for example
|Boxers|1|
|Shirts|2|
etc
I then use php to populate a array with this resource
eg
$myArr = arrary['Boxers', '1', 'Shirts', 2]
then I parse the array as a JavaScript array through an echo and .push() each element within a for loop
This JS array then becomes the argument of a JS function call.
As you can see below.
<?php
if(isset($_SESSION["username"])){
$cartArr = array();
$sql = "SELECT item, quantity FROM shop_cart WHERE user = 'Mike'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
array_push($cartArr,$row["item"],$row["quantity"]);
}
}
echo '<script> let paramArr = [];';
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push(' . "$cartArr[$x]" . ');';
}
echo 'cleanUpVue(paramArr);
</script>';
}
?>
The problem is that every element that is a String such as Boxers, Shirts keeps getting parsed as an HTML Collection and not just as a String. I'd like to know what I can do to avoid this behavior? As all I need is a JS array of String elements (4 as per the example) and nothing else
terrible what an obvious oversight on my part, I simply forgot to include quotation marks before concatenating the variable name, as such JS was trying to evaluate the original Strings as they also matched id's within the DOM
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push("' . $cartArr[$x] . '");';
}

Pass mysql table values to Javascript via PHP

I am trying to take all of the rows MYSQL table and ultimately have them end up in an interactive HTML table. I currently have no problem inserting values into my table using a $.post function, I just cannot return them, at least, not all of them.
Here is my JS code:
function load() {
$.post(
"Returnsmedb.php",
function (response) {
var firstname = response.fname;
var lastname = response.lname;
var username = response.uname;
var email = response.email;
var password = response.password;
console.log(response);
}, 'JSON'
);
}
PHP:
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "SME";
$password = "mypass";
$db = "p3";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pendingusers";
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// $response[] = $row[];
$response['fname'] = $row["fname"];
$response['lname'] = $row["lname"];
$response['uname'] = $row["uname"];
$response['email'] = $row["email"];
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>
I am thinking the easiest thing to do would be to store each row in an array, but I am not sure. It currently returns my $response array, but all of the values are null, except for 'email', which has the correct value, but it is from the last row of my DB table. Also, it only returns one row.
Any help / guidance would be much appreciated.
Thanks!
Your problem is that in this loop:
while($row = $result->fetch_array()) {
// $response[] = $row[];
$response['fname'] = $row["fname"];
$response['lname'] = $row["lname"];
$response['uname'] = $row["uname"];
$response['email'] = $row["email"];
}
You keep overwriting the same keys in $response, so at the end of the loop, only the values from the last DB row will be found. you could fix this by doing
while($row = $result->fetch_array()) $response[] = $row;
However if you'll be capturing all results, there is no need to loop through them. Just use fetch_all and you will get the full table right away.
$response = $result->fetch_all(MYSQLI_ASSOC)
As a sidenote, I would be really careful about sending everything unfiltered from your DB to the browser like this. Consider at least adding a LIMIT clause to your query so that if your table has thousands of rows, everything doesn't get sent:
$sql = "SELECT * FROM pendingusers LIMIT 50";
Finally, be explicit about the columns you want, so that you don't leak unwanted information if your DB gets new sensitive columns in the future
$cols = 'fname, lname, uname, email';
$sql = "SELECT $cols FROM pendingusers LIMIT 50";

Sending PHP array to JavaScript issue

I have an AJAX POST function that runs a PHP file that queries a MySQL database. It uses the "CONCAT" option in MySQL and then adds each row it receives into an array. I need to get that array from PHP to JavaScript, how would I go about doing this?
I've tried looking it up but nothing that I found either I didn't understand how to actually implement it, or it just flat out didn't work.
$sql_query = substr($sql, 0, -3);
$result = $connection->query($sql_query);
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$rowCount = mysqli_num_rows($result);
echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";
$bans = [];
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
I included that part of my PHP code if you need it.
I tried this:
echo(json_encode($bans));
.
success: function(data) {
document.getElementById('outputtext').innerHTML = '';
var array = new Array();
array = data;
document.getElementById('outputtext').innerHTML = array;
}
That returns everything, but adds a lot of "," between them.
Example of an index in the array:
[05-18] Daedalus banned EXAMPLE_USERNAME(EXAMPLE_GUID / EXAMPLE_IP) for EXAMPLE_REASON
I want all the lines from the $bans array to be put into an array in JavaScript.
When you usage echo(json_encode($bans)); that convert php array to json array. To use json in javascript you should first Parse that array like this
success : function(data){
result = JSON.parse(data) ;
}
Now you check this data console.log(result);
Access particular data through key like this
name = result.name;
This place in your code is wrong:
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
Because you cycle trough records with while and inside once more with for. Use only while:
while ($row = $result->fetch_row()) {
array_push($bans, $row);
}
Will pull all rows and without nulls.
In your case when you have only single column in your return from database you should use:
while ($row = $result->fetch_row()) {
array_push($bans, $row[0]);
}

How make query if some value is null and some are not while submitting data in php

I have type, state_name, city_name, location, name, price and squrefeet and I want to get result on their selection.
If I only select any one out of them or select all of them, where can I get the result of their selection?
I am taking one array and discard null value from array. But i don't know that its's true or not?
$state_name = $_POST["state_name"];
$city_name = $_POST["city_name"];
$location_name = $_POST["location_name"];
$type = $_POST["type"];
$area_from = $_POST["area_from"];
$area_to = $_POST["area_to"];
$price_from = $_POST["price_from"];
$price_to = $_POST["price_to"];
$room = $_POST["room"];
$a = compact('state_name', 'city_name', 'location_name');
print_r($a);
print_r(array_filter($a));die;
i hope this may help you:
if ($state_name!=null){
$search += 'state_name,'
}if ($city_name!=null){
$search += 'city_name,'
}
.
.
.
//do that for all of variable
$a = compact($search);

Trouble passing associative array from javascript to php and insert it into mysql database through prepared statements

http://jsfiddle.net/kqd7m5nb/
Just click on the insert data button, notice an alert box. This is an associative array. These are the values I want to pass into my php file.
In The php file, I get a Post value containing all the data I passed from my ajax data. I decoded It using json_decode. The data is now extracted as a php array of type stdClass. And I am now using prepared statements to insert all of the php array through the for loop statement.
Using Xdebug, the arrow stops inside the for loop of the php file. And after that, nothing gets inserted into my database. I also noticed when evaluating the 'count($value)' on php on xdebug, it returns 1 instead of 3. And evaluating $value[0]->fname in XDEBUG also returns an error.
sample.js
$('#ajax').click(function() {
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = "";
for (var i = 0; i < values.length; i++)
{
valuesDebug += " " + values[i]["fname"] + " " + values[i]["lname"] + " " + values[i]["point"] + "\n";
}
alert(valuesDebug);
var valueStringed = JSON.stringify(values);
$.ajax({
"type":"POST",
"url":"insertData.php",
"data":{value : valueStringed},
"success":function(data){
alert('Done inserting the current table values');
}
});
});
insertData.php
<?php
if (isset($_POST['value']))
{
$value = json_decode(stripslashes($_POST['value']));
}
$mysqli = new mysqli("localhost","root","password","test");
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)"); //NULL is auto increment primary key id
$stmt->bind_param('ssi', $fname, $lname, $point);
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->execute();
}
}
$stmt->close();
$mysqli->close();
?>
At a glance you need to be doing:
$stmt->bind_param('ssi', $fname, $lname, $point);
in your for loop as your defining them in the loop, if you do it above as you have - the variables are undefined.
So try:
$stmt = $mysqli->prepare("INSERT INTO team VALUES (NULL,?, ?, ?)");
if (count($value) > 0)
{
for( $i = 0 ;$i < count($value);$i++){
$fname = $value[$i]->fname;
$lname = $value[$i]->lname;
$point = $value[$i]->point;
$stmt->bind_param('ssi', $fname, $lname, $point);
$stmt->execute();
}
}
This code now works.
Please see my original javascript code.
It seems on this part I added an array valuesDebug and copied the contents from the values array through the push method. I don't know how exactly why this works. Is there a way to make this shorter?
BTW The first line is the row cell contents of my table being converted into the values array.
var values = $('#mytable tbody tr').map(function() {
return {
fname : $('td:eq(0)',this).text(),
lname : $('td:eq(1)',this).text(),
point : parseInt($('td:eq(2)',this).text())
}
});
var valuesDebug = [];
for (var i = 0; i < values.length; i++)
{
valuesDebug.push({fname: values[i]["fname"],lname: values[i]["lname"],point: values[i]["point"]});
}
var valueStringed = JSON.stringify(valuesDebug);
// passes valueStringed into ajax ...

Categories

Resources