I'm working on an Activation Queue for new accounts on my website.
The system will work by iterating through an array with each new user account details in and then display them so the Admin can either accept or deny the account. To collect the account details and display them in an array I'm using the following piece of code, however I get the error "array_push() expects parameter 1 to be array, null given". I have no clue why this is being caused and I have tried various things previously suggested. Thanks in advance.
<?php
session_start();
require "classes.php";
$TF = new TF_Core ();
$ActQueueQuery = "SELECT username, surname, forename, joined FROM users
WHERE rank = 'Unactivated'";
if ($statement = TF_Core::$MySQLi->DB->prepare($ActQueueQuery)) {
$statement->execute();
$results = $statement->get_result();
}
if($results->num_rows == 0){
$data = 1;
}
else{
$_SESSION["ActQueue"] = "";
while($row = $results->fetch_assoc()){
$_SESSION["ActQueue"] = array_push($_SESSION["ActQueue"], array($row["username"], $row["surname"], $row["forname"], $row["joined"]));
}
$data = 0;
}
echo $data;
?>
<?php
session_start();
$_SESSION["ActQueue"] = array(); // define an empty array
require "classes.php";
$TF = new TF_Core ();
$ActQueueQuery = "SELECT username, surname, forename, joined FROM users
WHERE rank = 'Unactivated'";
if ($statement = TF_Core::$MySQLi->DB->prepare($ActQueueQuery)) {
$statement->execute();
$results = $statement->get_result();
}
if($results->num_rows == 0){
$data = 1;
}
else{
while($row = $results->fetch_assoc()){
$_SESSION["ActQueue"][] = array($row["username"], $row["surname"], $row["forname"], $row["joined"]); // check the change
}
$data = 0;
}
echo $data;
?>
"You are overwriting $arr_foundits on $arr_foundits = array_push($arr_foundits, $it->ID);. Remove the $arr_foundits = as array_push does not return the array but an int." Musa
Related
So I am new to Angular2 and I can't figure this out. I declared an array and fill it up by checking checkbox. I want to send that array to PHP and use it to fill up a table.
This is my code for filling up the array.
selectedValue:Array<{name:string}>=[];
change(e, type) {
console.log(e.target.checked);
console.log(type.users); // users is of type User class that has attribute name
if(e.target.checked) {
this.selectedValue.push(type.name);
} else {
let updateItem = this.selectedValue.find(this.findIndexToUpdate, type.name);
let index = this.selectedValue.indexOf(updateItem);
this.selectedValue.splice(index, 1);
}
}
findIndexToUpdate(type) {
return type.name === this;
}
array has a list of names that I check off and now i send it to a method:
addioassign(){
this.userService
.insioassign(this.selectedValue)
.subscribe();
}
}
and in my service class:
insioassign(info){
return this._http.post("http://localhost/try/api/fill.php", info)
.pipe(map(() => ""));
}
my php rest api:
<?php
$data1 = json_decode(file_get_contents("php://input"));
include "db.php";
//$report_id = $data1->report_id;
$report_id = '8';
$sql="SELECT Eid FROM employee WHERE name IN ('$data1->name')";
if ($data1->name) {
$result = $conn->query($sql);
}
if ($result->num_rows > 0) {
// output data of each row
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
}
$r = count($data);
for($x = 0; $x < $r; $x++) {
$s = implode('', $data[$x]);
$sql1 = "INSERT INTO ioassign (report_id, Eid) VALUES($report_id, $s)";
$result1 = $conn->query($sql1);
}
$conn->close();
PLEASE HELP. I've been on this since the past week and a half. and have found no conclusive answer. I've tried everything I could.
$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.
So I made a query which returns many restaurants and I put them in a variable $row:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
When I try to run my code, it prints Array to string conversion.
The problem appears in this line:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
I searched about the error and I understand but I tried many resolutions and didn't solved the problem.
can someone help please?
You should do like the following
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
Try For PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];
The problem is in this statement
$idRestaurant = $stmt->fetch();
Have you tried $idRestaurant = $stmt->fetch()[0];?
You can actually check what's coming into $idResturant by checking it via var_dump
var_dump($idResturant)
Check this:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
To do this:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
The code below should send back an json with informations in a Database.
It takes two parameters grade and subject. The problem ist, when I use parameters are not in the database behind everything works as expected no entry, but if it would get an answer from the database nothing appears. I mean really nothing. The values i need are there i tried this and no errors are logged into the logging file. As server runs apache2 with php5.6.22 on Debian. I don't know what i did wrong. Hopefully someone can help me.
The Code:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".$subject." AND grade=".$grade;
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die();
}
$response = array();
$response['books'] = array();
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row ["fullname"];
$book['ISBN'] = $row ["ISBN"];
$book['id'] = $row ["id"];
array_push($response['books'], $book);
}
$response['response'] = "1";
print(json_encode($response));
die();
I think this might be your problem:
array_push($response['books'], $book);
as far as I know you can't push a variable into a specific index of an array since no key is provided for the item being pushed.
It would be better to do this as follows:
case 'get_books':
$grade = $_GET['grade'];
$subject = $_GET['subject'];
$sqlt = "SELECT * FROM book_type WHERE subject=".mysqli_real_escape_string((htmlspecialchars_decode($subject, ENT_QUOTES)))." AND grade=".mysqli_real_escape_string((htmlspecialchars_decode($grade, ENT_QUOTES)));
$sql = mysqli_query($db, $sqlt);
if(!$sql){
print(json_encode(array('response' => 2)));
die('sql failed');
}
$response = array();
$response['books'] = array();
$response['validator'] = 'valid';
$i = 0;
while($row=mysqli_fetch_assoc($sql)) {
$book = array();
$book['fullname'] = $row["fullname"];
$book['ISBN'] = $row["ISBN"];
$book['id'] = $row["id"];
$response['books'][$i] = $book;
$i++;
}
$response['response'] = "1";
var_dump($response);
//echo json_encode($response);
die();