jQuery Ajax - $sql is an object Error - php

UPDATE at bottom of question
I'm getting the error:
Warning: mysqli_query() expects parameter 2 to be string, object
given
Questions about this are incredibly common on Stack Overflow - my apologies in advance. I haven't been able to find a good answer for my specific problem. If there is a thread that addresses this, please let me know.
Here is my Ajax code:
$.ajax({
url: "get.php",
type: "post",
datatype: "json",
data:{ ajaxid: altCheck }, //this is an integer passed to MySQL statement
success: function(response){
console.log(response);
},
error: function(){
console.log("test");
}
});
get.php
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
var_dump($value); //checking to see what $value is at this point
$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?");
$sql->bind_param("s",$value);
//THIS LINE THROWS THE ERROR
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
?>
The fourth line of code var_dump($value); outputs string(0).
UPDATE: MySQLi
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
$query = $db->prepare('SELECT * FROM table WHERE screeningId = ?');
$query->bind_param('s', $_GET[$value]);
$query->execute();
if ($result = mysqli_query($db, $query)) {
while ($url = mysqli_fetch_object($result, 'imageURL')) {
echo $url->info()."\n";
}
}
?>
Screenshot of MySQL table data columns:

EDIT
Okay... 8 edits spent on mysqli... Enought!
Here is how I DO using PDO. And it WILL work first shot.
I have a separate file for the database connection info.
dbconnection.php:
(The advantage of the separate definition file is one place to update the user password when needed.)
<?php
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[DATABASE_NAME];host=127.0.0.1';
$user = '[DATABASE_USER]';
$password = '[USER_PASSWORD]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
?>
Now in your PHP files where a database request has to be done, include the PDO definition file, the just request what you want:
<?php
include('dbconnection.php');
// JUST TO DEBUG!!!
$_REQUEST['ajaxid'] = "1";
// Database request.
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
$stmt->bindParam(1, $_REQUEST['ajaxid']);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die;
}
// Looping through the results.
$result_array =[];
while($row=$stmt->fetch()){
array_push($result_array,$row['imageURL']);
}
// The result array json encoded.
echo json_encode($result_array);
?>

Since you are using mysqli_* all other place in your project, update your get.php as below.
<?php
$db = mysqli_connect("...", "...", "...", "...");
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
//var_dump($value); //checking to see what $value is at this point
$sql = "SELECT * FROM table WHERE screeningId = '$value'";
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
//output data
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
EDIT
With respect to bind param with mysqli,
<?php
$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');
$sql = 'SELECT * FROM table WHERE screeningId = ?';
$stmt = $conn->prepare($sql);
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$stmt->bind_param('s', $value);
$stmt->execute();
$res = $stmt->get_result();
$temp = array();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
array_push($temp,$row['imageURL']);
}
echo json_encode($temp);

Select Data With PDO in get.php:
<?php
if( isset($_POST['ajaxid']) ) {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table WHERE screeningId = :screeningId");
$stmt->execute(array(':screeningId' => $_POST['ajaxid']));
$row = $stmt->fetch();
}
?>
You configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $conn object:
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Related

Array won't print row data

I got this simple PHP code to print a Column from a database and it isn't working unfortually. Any ideas on what to do right?
I've tried to work on the while loop I have in the if statement but no luck
What im trying to get array to print like :
<?php
$input = $_POST['input'];
$servername = "localhost";
$username = "hawk_manager";
$password = "hawk_eyes";
try {
$pdo = new PDO("mysql:host=$servername;dbname=HawkCenter", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if ($input == "RoomNumber") {
$query = 'SELECT RoomNumber FROM rooms';
$statement=$pdo->prepare($query);
$statement->execute();
$roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
while( $roomnumbers=$statement->fetchAll(PDO::FETCH_ASSOC)){
echo "{$statement['RoomNumber']}";
}
}
$conn = null;
?>
You are doing it wrong, it should be
1. Selecting multiple rows
$data = $pdo->query("SELECT RoomNumber FROM rooms")->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo $row['RoomNumber ']."<br />\n";
}
2. Prepared Statements::
$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms WHERE id=?");
$stmt->execute([$id]);
$user = $stmt->fetch();
OR
$stmt = $pdo->prepare("$stmt = $pdo->prepare("SELECT RoomNumber FROM rooms LIMIT :limit, :offset");
$stmt->execute(['limit' => $limit, 'offset' => $offset]);
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row['RoomNumber']."<br />\n";
}

I want to write code for check if data already exits then insert in different table

I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp

Uncaught Error: Call to a member function fetchAll()

Guys i am trying to do a webservice for uni project. Everything seems ok untill i run the code and get this error Uncaught Error: Call to a member function fetchAll() on null . This is the code can anyone please tell me what is wrong with it?
<?php
header("Content-type: application/json");
$conn = new PDO("mysql:host=localhost;dbname=user;", "user", "pass");
$loc = $_GET["location"];
$type = $_GET["type"];
if(isset($_GET["location"]) && isset($_GET["type"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$loc' and type='$type'")
}
else if (isset($_GET["location"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$loc'");
}
else if (isset($_GET["type"]))
{
$result = $conn->query("Select * from resit_accommodation where location='$type'");
}
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
?>
If neither of the $_GET parameters is set, you never set $result to anything, so you'll get an error if you try to use it.
You should also use a prepared statement rather than substituting variables, to prevent SQL injection.
<?php
header("Content-type: application/json");
$conn = new PDO("mysql:host=localhost;dbname=user;", "user", "pass");
$stmt = null;
if(isset($_GET["location"]) && isset($_GET["type"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :loc and type= :type");
$stmt->execute(['loc' => $_GET['location'], 'type' => $_GET['type']]);
}
elseif (isset($_GET["location"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :loc");
$stmt->execute(['loc' => $_GET['location']]);
}
elseif (isset($_GET["type"]))
{
$stmt = $conn->prepare("Select * from resit_accommodation where location= :type");
$stmt->execute(['type' => $_GET['type']]);
}
if ($stmt) {
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$rows = [];
}
echo json_encode($rows);
?>

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Categories