PHP variable is not an mysqli object - php

I have the next code (compilated in NetBeans)
$query = 'INSERT INTO grupos(nombre, descripcion)'
. ' VALUES ("' . utf8_decode($_POST['name']) . '", "' . utf8_decode($_POST['desc']) . '")';
$result = $con->query($query) or exit("Error: " . $con->errno . ": " . $con->error);
if ($result->affected_rows > 0) {
Why I got this: "Trying to get property of non-object "
if when I made a echo $result; display a '1'?

From the documentation of mysqli::query():
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
Since your query is INSERT, not SELECT, it doesn't return a mysqli_result, it just returns TRUE. You should use $con->affected_rows instead of $result->affected_rows.

Related

codeigniter 4 not showing mysql full query when error occured

How to show full query string when occur errors. My query as follows
$builder = $this->table("$this->table");
$builder->select("usr_lock");
$builder->where("usr_lock >= '" . date('Y-m-d H:i:s') . "'");
$builder->where($this->primarykey, $user_id);
$r = $builder->get()->rowArray();
echo "<br>Error: " . $builder->error();
echo "<br>Last Query: " . $builder->getLastQuery();
return $r['usr_lock'];
When execute this, it is showing errors as 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 '= '1'' at line 4 . To know about the error I need to get full query. So I used $builder->getLastQuery(). But it is not executes. The page look like as
Use $builder->getCompiledSelect() before executing the $builder->get()
$builder = $this->table("$this->table");
$this->db_debug = FALSE;
$builder->select("usr_lock");
$builder->where("usr_lock >= '" . date('Y-m-d H:i:s') . "'");
$builder->where($this->primarykey, $user_id);
echo "<br>Last Query: " . $builder->getCompiledSelect(false);
exit();

PGAdmin succeeds but PDO query fails

I am wanting to get column information on a Postgres database table. I am using the following query:
select column_name as "Field", data_type as "Type", is_nullable as "Null", character_maximum_length as "max_length" from information_schema.columns where table_name='testempty'
(At some point, I will be removing the AS clauses. I had reasons for including them when I originally set up this query, but these reasons have since evaporated.)
When I run the query in PGAdmin, I get the results I expect: There are 2 columns, and I see their requested details. When I execute the same query using PDO in PHP, I get 0 rows back. No errors, the execute call returns true. Here is the PHP code:
try {
$remote_statement = $remote_con->prepare($column_query);
$remote_exec = $remote_statement->execute();
} catch(Exception $e) {
file_put_contents("logs/remote.log", '[' . date("Y-m-d H:i:s") . ' ' . $_SERVER["REMOTE_ADDR"] . "] Prepare failed: " . $e->getMessage() . "\n", FILE_APPEND);
}
if (!$remote_exec) {
file_put_contents("logs/remote.log", '[' . date("Y-m-d H:i:s") . ' ' . $_SERVER["REMOTE_ADDR"] . "] Execute failed\n", FILE_APPEND);
}
$remote_error = $remote_statement->errorInfo();
if (!empty($remote_error[2])) {
file_put_contents("logs/remote.log", '[' . date("Y-m-d H:i:s") . ' ' . $_SERVER["REMOTE_ADDR"] . "] Query failed: " . $remote_error[2] . "\n", FILE_APPEND);
die($remote_error);
}
$remote_rows = $remote_statement->fetchAll(PDO::FETCH_ASSOC);
$remote_con is a PDO connection object I created earlier in the code. $column_query is set to the query I listed above. There is another table I run this same code on prior to this and I get the expected results.
I appreciate any helpful hints here. I am sure I am missing something obvious, but it baffles me that the query works in PGAdmin and not via a PHP call.
This turned out to be a table-specific permissions issue. Granted SELECT permissions to PUBLIC for a problem table and the query via PHP worked. I found another pair of tables in a different database with this issue, and all was resolved by granting this permission.

PHP json_encode() adding extra double-quotes around Array Elements

I have an Array named $items that looks like the following:
array (
0 => '{"id":"1", "qty":"1", "price":"12.51"}',
1 => '{"id":"2", "qty":"2", "price":"25.02"}',
)
I'm trying to build a mySQL INSERT statement which includes the data in $items as follows:
$sql = 'INSERT INTO vals (id, items, timestamp)
VALUES (' . $id . ', "' . json_encode($items) . '", "' . date('Y-m-d H:i:s') . '")';
However, the INSERT into mySQL is failing due to json_encode() adding double-quotes around the Array Elements:
INSERT INTO
vals
(
id,
items,
timestamp
)
VALUES
(
1,
"[
"{\"id\":\"1\", \"qty\":\"1\", \"price\":\"12.51\"}",
"{\"id\":\"2\", \"qty\":\"2\", \"price\":\"25.02\"}"
]",
"2015-11-26 20:31:02"
)
It's the double-quotes before/after the curly-braces "{ ...data... }" that are the problem.
Is there a way to convert the Array to a String that will elimnate these extra quotes?
Thanks much for any guidance!
EDIT:
From the examples below, I'm trying to use mysqli prepared statements.
I'm executing the following:
$stmt->bind_param("i", (int) $id)
and am getting this error:
ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException'
with message 'Call to a member function bind_param() on a non-object'
I didn't get an error executing the following:
$stmt = $mysqli->prepare($sql)
so I'm thinking $stmt should be okay to call bind_param() on.
I looked at the PHP docs and don't believe I need to do anything else with $stmt. Does anyone see something I'm missing?
You either need to escape your json_encode'd string for use in the query, or use a prepared statement and bind the value to a parameter.
Your quotes around the individual array items are actually required as your individual array items are in fact strings... so all you need is to escape the entire value...
So either:
$sql = 'INSERT INTO vals (id, items, timestamp)
VALUES (' . $id . ', "' . mysql_real_escape_string(json_encode($items)) . '", "' . date('Y-m-d H:i:s') . '")';
or a better way of doing this:
$json = json_encode($items);
$sql = 'INSERT INTO vals (id, items, timestamp) VALUES (?, ?, ?)';
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare($sql))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->bind_param("s", $json)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->bind_param("s", date('Y-m-d H:i:s'))) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
EDIT
Also, #JoshJ is correct about your values being JSON strings... re-encoding a Json string will double escape everything. If this is not your intended use (i.e. retrieving the values as strings), then you should in fact try decoding each string to an associative array using:
foreach ($items as $key => $item) {
$items[$key] = json_decode($item, true);
}
This will give you an $items value of:
[
0 => [
"id" => "1",
"qty" => "1",
"price" => :"12.51"
],
1 => [
"id" => "2",
"qty" => "2",
"price" => "25.02"
]
]
There are other options of course for treating numeric string s as numbers in the output which you may also want to investigate...
See: http://php.net/manual/en/function.json-decode.php
EDIT 2
In Symfony, you may need to use the PDO bindParam() function syntax.
$sql = 'INSERT INTO vals (id, items, timestamp) VALUES (:id, :items, :datetime)';
$stmt = $pdoconnection->prepare($sql);
$stmt->bindParam(':id', $id);
etc...
See: http://php.net/manual/en/pdostatement.bindparam.php and http://php.net/manual/en/class.pdostatement.php
Note that from PHP 5.3.3 on, there's a flag for auto-converting numbers, while options parameter was added since PHP 5.3.0:
$arr = array( 'row_id' => '1', 'name' => 'George' );
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}
The simplest and safest answer for this is to switch to prepared statements. Documentation for that can be found here
If that doesnt work right with you, you can use simple built in methods for escaping characters.
If you are using MYSQL, you can make use of the mysql_real_escape_string function — It escapes special characters in a string for use in an SQL statement.
Be carefull, as this extension (MYSQL) was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
for MYSQLi, use mysqli::real_escape_string
A use case for your scenarial, i assume you are using the mysql extension:
$sql = 'INSERT INTO vals (id, items, timestamp) VALUES (' . $id . ', "' .mysql_real_escape_string(json_encode($items)). '", "' . date('Y-m-d H:i:s') . '")';
You can even use php's addslaches() function documented here. What it does is that it:
returns a string with backslashes before characters that need to be escaped. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

Php is not printing database information

I just set up a mysql data base, although my php isn't printing out the information that I want printed.
Here's what my code looks like (I've already connected to mysql and created a database successfully, I just need it to print out what I had inserted into it):
// will insert into the table
mysqli_query ($con, "INSERT INTO alarms(Title, Description, DT)
VALUES(getSucked, Agha will smd, 2013-08-05 00:15:12)");
//will print out what we just insert into the table, ie agha smd's
$result = mysqli_query($con,"SELECT * FROM alarms");
while ($row = mysqli_fetch_array($result))
{
echo $row['alarmID'] . " <br> " . $row['Title'] . " <br> " . $row['Description'] . " <br> " . $row['DT'];
}
//closing connection
mysqli_close($con);
echo "<br><br>connection has been closed";
The warning/error I keep getting is:
"Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in B:\DropBox\Dropbox\EbadlyAgha\Ebad\reminders.php on line 83"
Line 83 is where the while loop begins.
Your query failed to run. mysqli_query will return false if the query does not execute, hence the warning of mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given. You should always check the return value when interacting with the database, to make sure you are aware of what's going on. PHP will happily coerce many types into other types silently, so you have to be very proactive in your error checking.
mysqli_query returns FALSE on failure.
try
if ($result) {
while ($row = mysqli_fetch_array($result))
{
echo $row['alarmID'] . " <br> " . $row['Title'] . " <br> " . $row['Description'] . " <br> " . $row['DT'];
}
}
Change your Insert query to
mysqli_query ($con, "INSERT INTO alarms(Title, Description, DT)
VALUES('getSucked', 'Agha will smd', '2013-08-05 00:15:12')");
Your Insert query will fails when you gave the spaces.Try to put them in quotes..
Use
mysqli_query ($con, "INSERT INTO alarms(Title, Description, DT)
VALUES(getSucked, 'Agha will smd', '2013-08-05 00:15:12')");
and try to echoed query and run into phpmyadmin.because your value is with space so you have to use it in ''.

Why do I get a syntax error when embedding array elements in a string?

I am trying to INSERT some data into a database. I can do this on one FIELD just not on multiple. It seems to be a simple syntax issue. The error I get is:
Parse error: syntax error, unexpected ',', expecting ']'
The error is on the INSERT line:
<?php
$con = mysql_connect("local","username","password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("npsreviews", $con);
$sql="INSERT INTO burkett (DATE, STORE, 5STAR, 4STAR, 3STAR, 2STAR, 1STAR, TOTAL, NPS) VALUES ('$_POST[DATE]', '$_POST[STORE]', '$_POST[5STAR]', '$_POST[4STAR]', '$_POST[3STAR]', '$_POST[2STAR]', '$_POST[1STAR]', '$_POST[TOTAL]', '$_POST[NPS]')";
if (!mysql_query($sql,$con)){die('Error: ' . mysql_error());}
mysql_close($con)
?>
Thanks in advance, I cannot find the answer when looking for Multiple $POST.
First of all, you're missing quotes around the array indices; It should be $_POST["STORE"], not $_POST[STORE]. Secondly, you can't index arrays this way with string interpolation. You'll need to use {$...} syntax:
$x = array("key" => "value");
echo "The value of 'key' is '{$x["key"]}'";
Or concatenate the pieces of the string:
echo "The value of 'key' is '" . $x["key"] . "'";
Either method will produce:
The value of 'key' is 'value'
Note: I've answered your question as a simple syntax error, but this does not solve your real problem, which is rampant SQL injection vulnerability.
SQL query should look like this
$sql="INSERT INTO burkett (DATE, STORE, 5STAR, 4STAR, 3STAR, 2STAR, 1STAR, TOTAL, NPS) VALUES ('{$_POST["DATE"]}',
'{$_POST["STORE"]}', '{$_POST["5STAR"]}', '{$_POST["4STAR"]}', '{$_POST["3STAR"]}', '{$_POST["2STAR"]}',
'{$_POST["1STAR"]}', '{$_POST["TOTAL"]}', '{$_POST["NPS"]}')";
But in all your SQL query is prone to SQL Injection so I would recommend to clean your POST before doing something with it
read more about SQL injections here
You can clean your $_POST using this
$_POST = array_map('mysql_real_escape_string',$_POST);
Or use PDO and use prepared statements to accomplish sql INSERTS, UPDATES etc
escape it as so:
$sql= "INSERT INTO burkett (DATE, STORE, 5STAR, 4STAR, 3STAR, 2STAR, 1STAR, TOTAL, NPS) VALUES ('" . $_POST['DATE'] . "', '" . $_POST['STORE'] . "', '" . $_POST['5STAR'] . "', '" . $_POST['4STAR'] . "', '" . $_POST['3STAR'] . "', '" . $_POST['2STAR'] . "', '" . $_POST['1STAR'] . "', '" . $_POST['TOTAL'] . "', '" . $_POST['NPS'] . "')";

Categories