function insertNewBidPrice($code, $newBidPrice)
{
global $conn;
$sql = "update auctionitem set highestbid=$newBidPrice where code=$code";
//echo $sql;
if($conn->query($sql))
{
return 1;
}
else
{
require 0;
}
}
I have this php fuction that results 0 all time although update query successfully update the table.
I use PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Create a statement object first, using prepare.
$stmt = $conn->prepare($sql);
$worked = $stmt->execute();
if ($worked == TRUE) {
//I did stuff
} else {
// nope
}
function insertNewBidPrice($code, $newBidPrice) {
global $conn;
// write your query
$sql = "UPDATE auctionitem SET highestbid='$newBidPrice' WHERE code='$code'";
// run the query
$result = $conn->query($sql);
// check the result of the query
if ($result == true) {
// it was a success
return 1;
} else {
return 0;
}
}
global $conn;
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// it worked
}
Here you go this should do the trick. I noticed you say "require 0" in your if else statement it needs to be a return. Other then that i'm not sure on your problem but there are 2 possibilities i can think of.
Your $conn variable is invalid. Check it has the correct credentials, see the $conn->connect_error line, it is in the code i wrote but also here: http://php.net/manual/en/mysqli.connect-error.php.
Possibly the query incorrect. Personally i format everything with capitals ect. as my text editor colors it when i do that and it is easy for me to see what is what. Also there were no quotes surrounding the variables in your SQL statement, this is fine if it is an integer but if you are accidentally passing a string it will fail.
Also check that you have selected the correct table ect. in your SQL.
Related
EDIT. My error ONLY occurs when calling database connection as a function, if I call my database connection normally, the error do not occur.
I'm trying to execute a prepare statement with database connection as a function so that it can be reused inside other functions. Executing normal SQL codes work when using database connection function but I'm getting errors when I try to use in a prepare statement.
This is my code.
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
if (connect()->connect_error) {
die("Connection failed: " . connect()->connect_error);
} else {
echo "GOOD";
}
$val = "1";
$stmt = connect()->prepare("SELECT * FROM countries WHERE id = ?");
$stmt->bind_param("s",$val);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
$stmt->close();
When connecting database as a normal variable such as this works.
$stmt = $conn->prepare("SELECT * FROM countries WHERE id = ?");
However, I get "Call to a member function fetch_assoc() on bool" whenever I tried to call my connection as a function.
What am I doing wrong with this code?
After searching for a while and based on this answer, I was able fix my problem by declaring a variable for connection. However, this doesn't explain why directly calling connect doesn't work. Can somebody explain to me why the first way doesn't work?
$db = connect();
$stmt = $db->prepare("SELECT * FROM countries WHERE id = ?");
My Code is :
//Catch
$myotp=$_GET["myotp"];
$rowid=$_GET["rowid"];
//Constructing the updat esql query
$update= "update order set dsotp ='$myotp' WHERE fsotp='$myotp' and id_order=$rowid";
//Excecuting the query
$res=mysqli_query($conn,$update);
It is working fine. But the problem is how to know from PHP code that it is updated the table?
You can check this way:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
Refer:https://www.w3schools.com/php/php_mysql_update.asp
mysqli_query returns TRUE or FALSE. and also the result set.
So, you can try this:
print_r($res);
PS: Also for the second part you can use mysqli_affected_rows($conn); to get the number of affected rows.
If you want to test if the query executed succesfully you should use the if statements provided above, however these do not check if there was any value updated. If you want that, you should use affected_rows.
http://php.net/manual/en/mysqli.affected-rows.php
A basic example would be this:
if($result = $mysqli->query($sql)){
var_dump($mysqli->affected_rows);
if($mysqli->affected_rows == 1){
return TRUE;
} else{
return FALSE;
}
}
I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $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();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I've read for larger result sets I must use the MYSQL_USE_RESULT option when querying. This I do. However, the below PHP page is accessed via ajax and I receive 0 results once the known number of results reaches ~800. Before I reach this threshold, queries execute splendidly.
All queries work fine in phpmyAdmin.
What am I doing wrong?
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
}
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
?>
This had nothing to do with memory. Turns out the relation between larger query results and failing was purely statistical.
The real problem was that there were occasionally special characters in the data stored in the database. For some reason (perhaps someone can explain) PHP just stopped--no errors, no nothing when a special character was encountered. The field with the special character has collation: utf8_general_ci. I would have never thought this would be an issue... Perhaps someone can explain this as well.
Adding:mysqli_set_charset($conn,'utf8'); before the query fixed my problem entirely.
Edit your php.ini to let your server use more memory. Change memory_limit =128M to your desire value or add ini_set('memory_limit', '-1'); to your php code but this will tell the server to use all the memory it wants.
Try to use this:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
}
?>
In //Check connection you put if function. First statement is die() if $conn is error. In else statement of same if function you've puted nothing. Bottom part of code need to be inside else statement to work.
Try it.
try replace this
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
on this
if ($result = $conn->store_result()) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->free();
}
You use MYSQL_USE_RESULT to recive all rows from table?
The parts in bold are what I am questioning. Inside the search_for_new_user function, if I change $conn->prepare to $this->db_connection()->prepare. I receive a lost connection error. However in the function right above it db_conn_test I can use this syntax. In both cases I am returning the $connection so I don't understand why there must be a difference in syntax.
class Database {
function db_connection() {
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $connection = new mysqli($server, $user, $password, $database);
}
function db_conn_test() {
if (**$this->db_connection()->connect_errno**) {
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
}
function search_for_new_user($email) {
**$conn = $this->db_connection();**
if ($stmt = **$conn->prepare**("SELECT email FROM users where email = ?")) {
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
echo $result;
$stmt->close();
$conn->close();
}
}
}
In db_conn_test you call db_connection twice only if you got connection error during first db_connection call, so in this case connection to DB is not created.
But in search_for_new_user you create connection twice.
I.e.:
in db_conn_test:
// if connection not created, because you got error
if ($this->db_connection()->connect_errno) {
// therefore each time you call db_connection(),
// you again try create connection, and got same error
// and return it in die text
die($this->db_connection()->connect_errno . ": " . $this->db_connection()->connect_error);
} else {
echo "connected to mysql database";
}
but in search_for_new_user: you call db_connection() and create connection(if all is ok). And then if you call db_connection in second try, first connection is gone away and you got error.
Your class should looks like this:
class Database {
protected $connection;
function db_connection() {
if ($this->connection !== null) {
return $this->connection;
}
$server = "localhost";
$user = "user";
$password = "password";
$database = "database";
return $this->connection = new mysqli($server, $user, $password, $database);
}
}