Failed to assign variable taken from database to json array - php

I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.

When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.

I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.

Related

How do i successfully use function array_intersect() here?

I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}

PHP - Get the id of the table row clicked

I'm currently creating the account management system of my website and I decided to add a feature that enables me to declare weather a specific account is active or inactive. The data is retrieved from my mysql table.
$query = mysqli_query($DBConnect,"SELECT * from REG");
echo "<table class = 'table' style = 'width:90%;text-align:center'>";
while($getData = mysqli_fetch_assoc($query))
{
$username = $getData['uname'];
$fname = $getData['fname'];
$mname = $getData['mname'];
$lname = $getData['lname'];
$bday = $getData['bday'];
$email = $getData['email'];
$contact = $getData['contact'];
$gender = $getData['gender'];
if($getData['userlevel'] == 1)
{
$userlevel = "user";
}
else
{
$userlevel = "admin";
}
if($getData['status'] == 1)
{
$status = "active";
}
else
{
$status = "disabled";
}
echo "<tr>";
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
}
echo "</table>";
This is the content of status.php
session_start();
$DBConnect = mysqli_connect("localhost", "root","","kenginakalbo")
or die ("Unable to connect".mysqli_error());
$query = mysqli_query($DBConnect,"SELECT * from REG where id = '$_SESSION[id]'");
while($getData = mysqli_fetch_assoc($query))
{
$status = $getData['status'];
echo "'$_SESSION[id]'";
}
if($status == 1)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 0 where id = '$_SESSION[id]'");
}
else if ($status == 0)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 1 where id = '$_SESSION[id]'");
}
header("Location: admin/login.php");
What I need to do is get the ID of the row clicked and declare it in my session so that it can be used in the "status.php" file. But in this code, the last id in the table is the one that is declared into the session because of the loop. How do I get the value of the id of the row that is clicked? (is there sort of like onClick function in php? Thank you.
pass id parameter,
status.php?id=$id;
in status.php
$id = $_GET['id'];
Change:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
to:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php{$getData['id']}' >$status </a></td></tr>";
And in your status.php change $_SESSION['id'] to $_GET['id']. But make sure to first prevent SQL injection either through mysql_real_escape_string($_GET['id']) or through PDO.
There is no onclick function in PHP but you can create a form with a button on each row that holds the value of the row that it is in. Have that form simply do a post or a get request back to the status.php. Adding it to the session might be a bad idea.
Instead of a button you can also create a link modify your loop so that there is a property called $rowid and increment it within your loop.
Perhaps, what you really want is to use a GET superglobal here. You can switch
for
Then, you use $_GET["userid"] instead of $_SESSION[id] on the status.php page.
Also, you dont need a while for the status page. You should check the number of results, if it was 1 it means the user exists, and then you just do a $getData = mysqli_fetch_assoc($query) without the while

Premature End of Script Headers?

I have a problem with the code, it is the premature execution error when using header.
Code:
<?php
session_start();
require 'config.php';
$prepend = "<span class='welcome'>";
$append = "</span>";
if (!isset($_SESSION['name'])) {
header("Location: login.php");
}
echo $prepend."Здравей ".$_SESSION['name'].$append."</br>";
if (isset($_POST['submit']))
{
$newname = mysql_real_escape_string($_POST['newname']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$checkPass = "SELECT pass from admin WHERE pass = '$_POST[oldpass]'";
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data > 0)
{
$query = "UPDATE admin SET pass ='".$_POST['newpass']."',name ='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else {
header('Location: admin.php?failed=1');
}
}
?>
The first time when you open the page the else part is performed immediately and I can not understand why.
First you have 2 weird lines in your code:
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
Those function don't exist, in fact you probably used the mysql_...() ones, as it seems confirmed by the previous statements.
Now when you execute
$data = mysql_fetch_array($rs, MYSQLI_NUM);
then $data is an array (the next record returned) or FALSE (when no more record exist. And this statement should belong to a loop.
Anyway, in the current form of your code, when you execute if ($data > 0), it can't return anything significative since $data is an array.
So you must refactor all this piece of code according to your need (I guess you want to control that pass was really found by the previous query).
the first time you open page, the else part is executed because the session variables are not set, you need to set session variables first.
$_SESSION['sessionName']= $value;
you must have done this on some other page, if so, then please share the code.
and try using
if(mysqli_num_row($data)>0)
{
$query = "UPDATE admin SET
pass='".$_POST['newpass']."',name='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else{
header('Location: admin.php?failed=1');
}
}
?>

Array objects not being printed in input fields and sql query not receiving the id value

I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];

Returning a variable that has to be updated from a function, not returning?

There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}

Categories