This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am getting the following errors when i am trying to insert parsed data into a table in my database:
PHP Notice: Undefined index: manu in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined index: partnumber in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined index: description in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined property: DatabaseManager::$_link in /home/svn/dev.comp/Asus.php on line 112
PHP Warning: mysql_query() expects parameter 2 to be resource, null given in /home/svn/dev.comp/Asus.php on line 112
Here is the code i have so far:
<?php
//Declaring all database connection information
$username = "username";
$password = "password";
$database = "database_name";
//Setting connection to database, fail if could not connect
$link = mysql_connect("localhost", $username, $password) or die("Could not connect to database");
mysql_select_db($database, $link);
$csv = new CSVManager();
$data = $csv->get_data_array();
$api = new DataGrabber($link);
$xmldata = $api->call_api($data);
$dm = new DatabaseManager();
$dm->insert_asus_data($xmldata);
//This class will pull data from the .CSV file and store it inside an array
class CSVManager {
public function get_data_array() {
//Open and declare location of .CSV file to pull data from
$hook = fopen('asus.csv', 'r');
//Number of columns in .CSV file we are getting data from
$allowedCols = 5;
//Store all data we will extract, into an array
$data = array();
//Count the number of lines in the .CSV file
while($line = fgetcsv($hook)) {
$numcols = count($line);
//Test wether the number of columns we are declaring, is equal to the number of columns in the .CSV file
if($numcols == $allowedCols) {
//If so, assign each data row from the column names to new entries which will be declared in the DatabaseManager Class
$entry = array(
'man' => $line[0], //index of column name in .CSV file
'cat' => $line[1],
'model' => $line[2],
'family_id' => $line[3],
'family' => $line[4]
);
//Insert all entries into the data array declared above
$data[] = $entry;
}
}
//Once data is inside the array, return this data
return $data;
}
}
//This class will pull data from the XML document and store it inside another array
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/". "E%20Series" . "/" . rawurlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
It works fine upto here, but with the following code below it throws the errors above:
class DatabaseManager {
public function insert_asus_data($partbind) {
//create a new MySQL statement to insert data into the database table. Bind the entries declared above from both classes, to the fieldnames in the database and insert them as values.
mysql_query("INSERT INTO asus_parts (manufacturer, partNumber, description) VALUES ('{$partbind['manu']}', '{$partbind['partnumber']}','{$partbind['description']}')", $this->_link);
}
}
?>
They are both in the same file.. I dont understand why it is throwing these errors and how can i overcome this? Thanks.
[EDIT]
Here is one of the print statements:
[5] => Array
(
[productnumber] => 0
[partnumber] => 0B200-00120100
[description] => ME370T BAT COSLI LI-POLY FPACK
[manu] => Google
)
[6] => Array
(
[productnumber] => 1
[partnumber] => 0B200-00120200
[description] => ME370T BAT COSLI LI-POLY FPACK
[manu] => Google
)
Still does not insert any data in the table
The query is wrong you don't need the link in insert query change it to this
mysql_query("INSERT INTO asus_parts (manufacturer, partNumber, description) VALUES ('{$partbind['manu']}', '{$partbind['partnumber']}','{$partbind['description']}')");
You must escape your variables.
'{$partbind['manu']}'
This is shown as '{$partbind['
To escape the second quote just double it:
'{$partbind[''manu'']}'
Related
This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
How is it possible to store result of a query into an array? For example, the following code will produce this error:
Fatal error: Uncaught Error: Cannot use object of type stdClass as
array in C:\XAMPP\htdocs\php_test\test.php:50 Stack trace: #0 {main}
thrown in C:\XAMPP\htdocs\php_test\test.php on line 50
const PATH_TO_SQLITE_FILE = 'my_db.sqlite';
$pdo = new \PDO("sqlite:" . PATH_TO_SQLITE_FILE);
$queryy = $pdo->query('SELECT Title, Format '
. 'FROM Objects');
$arr = [];
while ($row = $queryy->fetch(\PDO::FETCH_OBJ)) {
$arr[] = [
'Title' => $row['Title'], // Error occurs here.
'Format' => $row['Format']
];
}
//echo $arr[1]->Title;
I've been stuck with this issue all morning and I haven't found the solution on Google. I hope someone can pinpoint what I'm not understanding.
You are fetching an object and then trying to access it as if was an array. Either fetch an array PDO::FETCH_ASSOC or access the object $row->Title.
However, your code could be minimized to this:
$queryy = $pdo->query('SELECT Title, Format FROM Objects');
$arr = $queryy->fetchAll(PDO::FETCH_ASSOC);
In my Android app I am using volley to echo my response which should be of the form:
[
{
"category":"whatever",
"name":"whatever",
"phone":"whatever",
"comment":"whatever",
"reviewid":32
},
{
"category":"whatever",
"name":"whatever",
"phone":"whatever",
"comment":"whatever",
"reviewid":76
}
]
Instead I am getting as the response:
Warning: Invalid argument supplied for foreach() in php file on line 13
I don't know if I'm posting it wrong from java or if the problem is with my php.
In my app I have:
selectOwnUserReviews = Arrays.toString(category.getUserReviewIds());
When I toast selectOwnUserReviews I can see selectOwnUserReviews is of the format like:
[63,59,42] or [234] or [34,29] etc...
I am trying to post the selectOwnUserReviews array with volley to my php with:
#Override
//post info to php
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//KEY_REVIEWID_USER is reviewiduser
params.put(KEY_REVIEWID_USER, selectOwnUserReviews);
return params;
}
Here's my php:
<?php
require('file.php');
$ReviewID = $_POST['reviewiduser'];
$results = array();
foreach($ReviewIDs as $ReviewID) {
$sql2 = "SELECT * FROM review WHERE review_id = ?";
$stmt2 = $con->prepare($sql2) or die(mysqli_error($con));
$stmt2->bind_param('i', $ReviewID) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();
//if user_id has reviews in the db
while($row = mysqli_fetch_array($result2)) {
//make an array called $results
$results[] = array(
'category' => $row['cat_name'],
'name' => $row['name'],
'phone' => $row['phone'],
'comment' => $row['comment'],
'reviewid' => $row['review_id'],
);
}
}
$json = json_encode($results);
echo $json;
?>
Line 13 in my php code is:
foreach($ReviewIDs as $ReviewID) {
Different variable names!
$ReviewID = $_POST['reviewiduser']; //without final s
foreach($ReviewIDs as $ReviewID) { //with final s.
/* ^ */
Edit:
You say you're still having problems.
Probably your $_POST is a string. Try:
$reviewIDs = json_decode($_POST['reviewiduser']);
that will probably make $reviewIDs a proper array to work with foreach.
You're getting the foreach error when posting with Android Volley to your php b/c all input values are strings in PHP and you can not foreach a string.
You perhaps first want to decode the string into an array which you then can foreach over. But if that is inteded by you or not was not clear to me from your question so I can not be very specific about that w/ my answer and only provide this as a general hint. It is often common to decode JSON, but please that must not be the case in your case: http://php.net/json_decode.
Next to that also take care you are using actually the correct variables, as others have pointed out and I'm with them, you need to use the exactly correctly written variable name, even one character off will give you a different variable name which will evaluate to NULL in PHP which you can't foreach over as well like w/ the string.
I was posting from Java to Php as a string and treating it in php like it was an array.
In Java I was posting selectOwnUserReviews which was of the format like "[1,34,78]". It looked like an array but was all treated as one unit. And even if I tried operations in php I was doing it on [1 and 34 and 78], not on 1 and 34 and 78.
So in Java I did:
//convert [56,23,87] to a string
selectOwnUserReviews = Arrays.toString(category.getUserReviewIds());
//remove [ and ] so we have a string of 56,23,87
selectOwnUserReviews = selectOwnUserReviews.substring(1,selectOwnUserReviews.length()-1);
Now I have the string 56,23,87 and I post this string to my php. In my php I use explode to get the individual values, my complete code looking like:
<?php
require('file.php');
$ReviewID = $_POST['reviewiduser'];
$ReviewID = explode(",",$ReviewID);
$results = array();
foreach($ReviewID as $ReviewID) {
$sql2 = "SELECT * FROM review WHERE review_id = ?";
$stmt2 = $con->prepare($sql2) or die(mysqli_error($con));
$stmt2->bind_param('i', $ReviewID) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();
while($row = mysqli_fetch_array($result2)) {//make an array called $results
$results[] = array(
'category' => $row['cat_name'],
'name' => $row['name'],
'phone' => $row['phone'],
'comment' => $row['comment'],
'reviewid' => $row['review_id'],
);
}
}
echo json_encode($results);
?>
Job done.
To expand on the other answers and give a more complete response based on the comments.
As you noted var_dump($_POST) results in the following:
array(1) {
["reviewiduser"]=>
string(4) "[63]"
}
Meaning that your post value is being received as a string of 4 characters, in the format of an array. Rather than the desired array of integers. However you can use json_decode on the value to parse the string into the desired array of integers.
Example: https://3v4l.org/64v30
Since we should never trust the data from the end user, especially cross-platform/site, you should sanitize and validate the data prior to processing it.
Additionally you have a mix of procedural and object oriented uses of mysqli with some missing controls of where mysql can return false or null. It is best to only utilize one style to ensure that your code is cohesive/coherent. As well as cover all cases where a function/method call may return a value other than what is desired, to be better anticipate the desired behavior or failure.
<?php
require __DIR__ . '/file.php';
//ensure the desired post key exists otherwise set a default value
if (!array_key_exists('reviewiduser', $_POST)) {
$_POST['reviewiduser'] = '[]';
}
//ensure json decode returns as the desired data type
$ReviewIDs = json_decode($_POST['reviewiduser']);
if (!is_array($ReviewIDs)) {
$ReviewIDs = [];
}
//declare results for use with json_encode
$results = [];
//declare ReviewID as a variable for use with bind_param
$ReviewID = null;
//prepare the database query for multiple executions
$sql2 = 'SELECT cat_name AS category, name, phone, comment, review_id AS reviewid FROM review WHERE review_id = ?';
//create a statement for use with prepare
$stmt2 = $con->stmt_init();
$stmt2->prepare($sql2) or die($con->error);
//bind ReviewID by reference so that it changes for each execute iteration
$stmt2->bind_param('i', $ReviewID) or die ('MySQLi-stmt binding failed ' . $stmt2->error);
//iterate over ReviewIDs
foreach ($ReviewIDs as $ReviewID) {
//validate the value is of the desired type
if (!is_numeric($ReviewID)) {
continue;
}
$stmt2->execute() or die ('MySQLi-stmt execute failed ' . $stmt2->error);
$result2 = $stmt2->get_result() or die('MySQLi-smt get_result failed' . $smt2->error);
//ensure a result is retrieved from the database
if ($row = $result2->fetch_assoc()) {
$results[] = $row;
}
}
$stmt2->close();
echo json_encode($results);
exit;
Wonder if you can help me figure this out. Latest PHP in WordPress 3.92. WordPress is using MySqli. I am trying to change my custom MYSQL to MYSQLI which should really be simple enough, but is throwing up so issues.
Below are 2 examples. Example 1 is using WordPress built in MYSQLI connection inside a function and the one underneath is my own. The first one throws up errors as shown but my own one does not.
function name{
global $wpdb;
$options = array();
$res=mysqli_query($wpdb,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($wpdb,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
Here are the errors i get
Warning: mysqli_query() expects parameter 1 to be mysqli, object given eval()’d code on line 3
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given eval()’d code on line 4
and here is it working with my own connection and no errors.
function name(
$dbhost1 = 'localhost';
$dbuser1 = 'user';
$dbpass1 = 'pass';
$dbname1 = 'DBName';
$conn=mysqli_connect($dbhost1 ,$dbuser1,$dbpass1,$dbname1);
$options = array();
$res=mysqli_query($conn,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($conn,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
I must be looking to hard as I cannot see why this would not work in the first instance to save having to create a new connection inside every function.
Many thanks
P
The first argument of mysqli_query is expected to be a mysqli connection object. $wpdb is not a mysqli connection object, it is the wordpress database object. That being said, you could just do $wpdb->get_results("select ID,County from counties ORDER BY County ASC"); instead, given that the query is proper.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am new to php and I am following the book 'PHP for absolute beginners' by Jason Lengstorf and it walks you through on how to make a basic blog website.
the code that it has showed me has had a lot of errors and because I am new to php I have a hard time debugging the code.
so I get this warning: Warning: array_push() expects parameter 1 to be array, boolean given in C:\xampp\htdocs\simple_blog\inc\functions.inc.php on line 76
here is the function where it is failing
function retrieveEntries($db, $page, $url=NULL)
{
/*
* If an entry URL was supplied, load the associated entry
*/
$fulldisp = NULL;
$e = array();
if(isset($url))
{
$sql = "SELECT id, page, title, entry
FROM entries
WHERE url=?
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute(array($url));
// Save the returned entry array
$e = $stmt->fetch();
// Set the fulldisp flag for a single entry
$fulldisp = 1;
}
/*
* If no entry ID was supplied, load all entry titles for the page
*/
else
{
$sql = "SELECT id, page, title, entry, url
FROM entries
WHERE page=?
ORDER BY created DESC";
$stmt = $db->prepare($sql);
$e = $stmt->execute(array($page));
//$e = NULL; //Declare the variable to avoid errors
// Loop through returned results and store as an array
while($row = $stmt->fetch()) {
if($page=='blog')
{
$e = $row;
$fulldisp = 0;
}
else
{
$e = $row;
$fulldisp = 1;
}
}
//var_dump($row);
/*
* If no entries were returned, display a default
* message and set the fulldisp flag to display a
* single entry
*/
if(!is_array($e))
{
$fulldisp = 1;
$e = array(
'title' => 'No Entries Yet',
'entry' => 'This page does not have an entry yet!'
);
}
}
// Add the $fulldisp flag to the end of the array
//var_dump($e);
array_push($e, $fulldisp); // line 76
return $e;
}
I know that based on the message the varriable $e is a boolean that has the value of false because I used var_dump($e) which I then commented out. But before line 76 there is an if statement: if(!is_array($e)) which checks if $e is not an array which it would not be because $row is a bool(false) and that is assigned to $e. So I assume that because a boolean value is not an array it will enter this statement: if(!is_array($e)) and in the body of that which is just before the error on line 76 turns $e back to an array
I know this may be really confusing but I really appretiate any help thank you.
$e is not guaranteed to be an array in your code, there are several code paths that would yield a non-array value of $e.
My guess is on this line
$e = $stmt->fetch();
or
$e = $stmt->execute(array($page));
is where the non array value is being set.
Test to see if $e is an array prior to using it as one, or structure the code where all code paths result in $e being an array.
$e = $stmt->execute(array($page)); Is this the issue? Why use $e here?
You need to if($stmt->execute(array($page))){ ... }.
This question already has answers here:
mysqli::query(): Couldn't fetch mysqli
(4 answers)
Closed 9 months ago.
I started using mysqli_* functions instead of the old mysql_* functions in PHP, and I'm having a bit of a problem with this code:
public function addUser($table, $code = false, $rows = false) {
if (!$code) {
header("Location: " . $this->authenticate());
} else {
$this->getToken($code);
}
$user = $this->getEndpoint('users/current', false, true);
$user = $user->response->user;
if (!$rows)
$rows = array(
"remote_id" => $user->id,
"firstName" => $user->first_name,
"lastName" => $user->last_name,
"photo" => $user->photo->medium,
"gender" => $user->gender == 'male' ? 1 : 2,
"email" => $user->contact->email,
);
$rows['access_token'] = $this->accessToken;
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'"); //line 136
$stmt->execute(); //line 137
}
The code returns these 2 errors:
Warning: mysqli::prepare(): Couldn't fetch MySQL in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 136
Fatal error: Call to a member function execute() on a non-object in C:\Users\Grega\Server\application\inc\classes\APIConnect.php on line 137
What is the reason for 'Couldn't fetch MySQL'? The database connection is correct, it works in other classes, and the query returns a valid result, if I echo it and execute it in phpMyAdmin. Also, my variable is named mysql NOT mysqli!
You should read more about the difference between MYSQL to MYSQLi.
While your code is:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = '{$this->accessToken}'");
You should do it like this:
$stmt = $this->mysql->prepare("SELECT id FROM users WHERE access_token = ?");
$stmt->bind_param("s" , $this->accessToken ); //Used 's' as I guess that the accessToken is a string
The binding part is the critical part of the prepare thing. (Your queries are safe)
After that you can use $stmt->execute(); and get_result().
For the first error: you probably closed the connection somewhere before this code, and this is why ($stmt -> close() )
For the second error: when you use (prepare()), you first introduce a SQL template to the database, which then has to pass the parameters to the "bind_param()" method to send it to the database with another protocol (to prevent SQL injection) and reduce the request and attach the parameters to SQL with execute() method