Can't Read static::$table_name after looping [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I get the following error messages:
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Sample 1
Sample 2
When using the following code:
public function __construct(){
global $MySQLDatabase;
global $news;
$this->dbh = $MySQLDatabase->open_connection();
// Convert Table Fields in to Attributes
static::$db_fields = $this->get_dbFields(static::$table_name);
foreach(static::$db_fields as $field){
$this->$field = "";
}
}
// Get Table Fields from the Database
public function get_dbFields($table_name){
$sql = 'DESCRIBE ' . $table_name ;
$query = $this->dbh->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
// Get the quantity of the Table Columns
$count = count($result);
$field = array();
// Loop through each column to get the 'Field'
// ($count - 1) -> $count is minus 1 because array count starts with zero
// Example : Table Have 8 Columns
// $count will read it as 1 - 8 while array ($result[i]) reads it as 0 - 7
for($i = 0; $i <= ($count - 1); $i++){
$field[] = $result[$i]->Field;
}
return $field;
}
Can anyone explain to me why I am having those errors above but still can get the output (Sample 1 and Sample 2) above?
Here is my Complete Code: http://pastebin.com/xypkzs30

The problem is in the method DatabaseObjects::instantiate. The first line says
$object = new self;
Now, self is a reference to the current class, that means the class in which the instantiate-method is implemented (DatabaseObjects) and not the class on which it is called.
So you don't create new News objects where the table_name is defined but DatabaseObjects objects which have no table_name defined.
You can resolve this by creating new instances using the "late static binding"-version:
$object = new static;
That way the method creates new News objects. You might want to also mark the DatabaseObjects class as abstract, so no accidental instantiation occurs.
Plus you might want to globally cache the get_dbFields method - otherwise you hit the DB for every instantiation of the News class (your users might fall asleep using your app).

Related

PDO param is reading as a string and not an int [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 5 years ago.
I want to pass a GET var into the query to set the OFFSET.
try {
$sql_offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
$main_query = "SELECT * FROM Orders
LIMIT 150 OFFSET :offset";
$result = $db->prepare($main_query);
$result->bindParam(':offset', $sql_offset, PDO::PARAM_INT);
$result->execute();
} catch (Exception $e) {
$error = $e->getMessage();
echo "<h2>".$error."</h2>";
die();
}
The query fails and the error message received is:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''450'' at line 2
Note: If I place 450 directly into the query it works fine.
It seems to me that the problem is that it is reading the param as a string '450' and not an int 450. I tried solving that with the PDO::PARAM_INT - didn't help. I parsed the value with (int)$sql_offset and int_val($sql_offset) and didn't help. Meaning, I was still receiving the same error message.
Question: am I right? Is the problem that it is seeing as a string? If so, how can I fix?
Or is there a different problem here?
Try to parse value in int then check:
$sql_offset = (int)(isset($_GET['offset']) ? $_GET['offset'] : 0);

i get sql syntax error and dint match any of suggested answer

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''dashboards' (employ_id,system_id,on-time,off-time,is_active) values ('Array' at line 1
public function admin_dashboard($id=null) {
$this->loadModel('Employ','System');
if ($this->request->is('post')) {
//debug($this->request->data);exit;
$employId = $this->request->data['Dashboard']['employ_id'];
$systemId = $this->request->data['Dashboard']['system_id'];
$logon = $this->request->data['Dashboard']['on-time'] = date("Y-m-d H:i:s");
$logout = $this->request->data['Dashboard']['off-time'] = date("Y-m-d H:i:s");
$active = $this->request->data['Dashboard']['is_active'];
//$date=date("Y-m-d H:i:s");
for($i=0;$i<count ($systemId);$i++){
$this->System->query("insert into 'dashboards' (employ_id,system_id,on-time,off-time,is_active) values ('$employId','$systemId[$i]','$logon','$logout','$active')");
//$var_dump($date);
}
$this->Session->setFlash(__('The query has been saved.'));
return $this->redirect(array('action' => 'admin_dashboard'));
}/* else {
$this->Session->setFlash(__('The query could not be saved. Please, try again.'));
}*/
$employs = $this->Employ->find('list');
$systems = $this->System->find('list');
$this->set(compact('employs','systems'));
}
The MySQL identifier quote character is the backtick
The first error in the question is because the quote character of MySQL is the backtick not a single quote.
i.e. valid:
mysql> SELECT * FROM `select` WHERE `select`.id > 100;
Invalid:
mysql> SELECT * FROM 'select' WHERE 'select'.id > 100;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''select' WHERE 'select'.id > 100' at line 1
mysql>
There are literally thousands of similar questions on stack overflow, as it's a common mistake.
There is no need to use query
However that's not the biggest problem/mistake in the question code. Model::query is designed/expected to be used for:
SQL calls that you can’t or don’t want to make via other model methods
Inserting data into the db does not fall into that category; Effectively it should be used as a last resort (generally speaking it is very rare to need to use this method).
Something similar to this is all that's required:
$this->loadModel('Dashboard');
$data = [];
foreach ($this->request->data['Dashboard']['system_id'] as $systemId) {
$row = $this->request->data['Dashboard'];
$row['system_id'] = $systemId;
$data[] = $row;
}
$this->Dashboard->saveMany($data);
saveMany is one of the standard ways to save data, and the most appropriate given the info in the question.
Note that if the logic is any more than a few lines of code it should not be in a controller action at all, and moved to the model instead e.g.:
// in controller
$this->Dashboard->myMethod($data);
// in the Dashboard class:
public function myMethod($input)
{
... whatever is necessary ...
return $this->saveMany($data);
}

update query throws error in mysql [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I have a table named 'mostread' with 2 columns open_id(int) and read(int). Now the problem is if 'open_id' is already present in the table then i need to update the 'read' for every click else i need to insert a new row with 'open_id' retrieved from the controller and read=1. I am using the below code in my model which inserts a new row properly but the second time i click it throws an error as follows.
A Database Error Occurred
Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read = read+1 WHERE open_id = '193'' at line 1
UPDATE mostread SET read = read+1 WHERE open_id = '193'
Filename: D:/Xampp/htdocs/opunletter/opunletter/application/models/Select.php
Line Number: 52
public function click($id)
{
$query = $this->db->query("SELECT * FROM mostread WHERE open_id='$id'");
$count= $query->num_rows();
if($count > 0) {
$this->db->set('read', 'read+1', FALSE);
$this->db->where('open_id', $id);
$this->db->update('mostread');
$data = array(
'open_id' => $id,
'read' => '1'
);
$this->db->insert('mostread', $data);
return TRUE;
}else{
return FALSE;
}
}
Try adding backticks arround read its a reserved keyword in mysql
$this->db->set('`read`', '`read` + 1', FALSE);

How can I fix a php function bool? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I dont know what is the problem with this function:
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return (mysql_result($query, 0) == 1) ? true : false;
}
This function was supposed to return true if the date('d.m.Y') equals the date in mysql.
Im using like this:
$data = date('d.m.Y');
if(server_grafico_expirar($data)){
echo "Today, is the date!";
}
The error is:
Parse error: syntax error, unexpected T_IF in /home/mcser325/public_html/checker.php on line 35
Firstly, you must make sure that the settings table does contain a row that has the data_exp column set to todays date in the format d.m.Y.
mysql_result retrieves the contents of one cell from a MySQL result set. The cell that you are retrieving is data_exp. From your question I have assumed that data_exp is a date in the format of d.m.Y.
With that said, mysql_result($query, 0) will never be equal to 1 as it will return the date you are selecting. You could approach this in two ways, you could either check if the cell equals $data and then return true
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return mysql_result($query, 0) == $data;
}
You could also check how many rows are returned. If more than zero rows are returned then you can return true.
function server_grafico_expirar($data) {
$data = sanitize($data);
$query = mysql_query("SELECT `data_exp` FROM `settings` WHERE `data_exp` = '$data'");
return mysql_num_rows($query) > 0;
}
Please note that the mysql extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
Aside from any other potential errors, what your PHP parser is saying is that there is a syntax error. It's not in what you showed us at least, but make sure that you've closed every corresponding curly brackets ({ }) and they are properly matched up and that all lines end with a semicolon (;).
I'd suggest indenting properly to find the error more easily.

Can't save $_POST array to database with function

I have a form that has multiple inputs of the same name, resulting in an array. I want to pass this $_POST array to a function which will process and save the array into a database.
I've done this before with no problems without using a function, but now that I want to contain it all in a nice neat function call it won't do it and I'm not sure why?
The input/post variable in question is named option[] and is passed to the function as $_POST['option']. Here is the function:
function newVariant($name, $option) {
global $db;
global $table_prefix;
$table = $table_prefix . "variants";
$query = $db->prepare("INSERT INTO $table(name) VALUES(:name)");
$query->bindParam(":name", $name);
if (!$query->execute()) {
die(showMessage("Error!","There has been a problem saving your variant. Please try again or contact technical support if the problem persists.",""));
}
$variant_id = $db->lastInsertId('id');
for($i = 0; $i < count($option); $i++) {
if($option[$i] != "") {
$table2 = $table_prefix . "variant_items";
$query2 = $db->prepare("INSERT INTO $table2(variant, option) VALUES(:variant, :option)");
$query2->bindParam(":variant", $variant_id);
$query2->bindParam(":option", $option[$i]);
if (!$query2->execute()) {
die(showMessage("Error!","There has been a problem saving your variant. Please try again or contact technical support if the problem persists.",""));
}
}
}
$redirect = renderLink("/beyond/?act=admin&sub=variants", "true");
showMessage("Saving variant...<META HTTP-EQUIV=\"Refresh\" Content=\"1; URL=$redirect\">","","");
}
This is the error I'm getting in my log:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option) VALUES(?, ?)' at line 1' in /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php:131
Stack trace:
#0 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php(131): PDO->prepare('INSERT INTO bb_...')
#1 /Users/adampcollings/Sites/Hot Mint Development/beyond/html/admin/new-variant.php(5): newVariant('Test', Array)
#2 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/html.php(19): include('/Users/adampcol...')
#3 /Users/adampcollings/Sites/Hot Mint Development/beyond/html/admin.php(10): subElement('admin', 'new-variant')
#4 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/html.php(8): include('/Users/adampcol...')
#5 /Users/adampcollings/Sites/Hot Mint Development/beyond/index.php(14): siteElement('a in /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php on line 131
Based on the comment thread above, there are several things you should try.
First, always enable error reporting when debugging an application. To do this in your script, add:
error_reporting(E_ALL);
to the top of your script.
Second, ensure that $options contains the data you expect. Somewhere in your code, add the following line:
var_dump($options);
This will show you the contents of $options. If it does not contain the values you expect, check your submission process.
Finally, if $options contains the expected data, check your table structure to ensure that your query matches and inserts the correct values.
EDIT: After you posted the MySQL error, I cross-checked the MySQL Reserved Words list. The word 'option' is on the list. As such, the query is failing because the word is not recognized as a column name. Try surrounding the column name with backticks:
$query2 = $db->prepare("INSERT INTO $table2(`variant`, `option`)...

Categories