Using the PHP manual I created following code:
$query = "INSERT INTO inserir(nome) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->$query);
I also used this answer for class connections: Error mysqli_select_db
But I keep getting this error:
Warning: mysqli_insert_id () expects parameter exactly 1, 2 given in
/home/controle/public_html/demo/teste.php on line 9
How do I fix that?
Here is the simple example for getting the id of last record created-
Code is taken from here
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Edit: Here is working code
<?php
define("SERVIDOR_BD", "localhost");
define("USUARIO_BD", "usuario");
define("SENHA_BD", "senha");
define("BANCO_DE_DADOS", "dados");
class conecta {
public $database_bancoDados = null;//1. New Added Field
public $bancoDados = null;//2. New Added Field
function conecta($servidor="", $bancoDeDados="", $usuario="", $senha=""){
if (($servidor == "") && ($usuario == "") && ($senha == "") && ($bancoDeDados == "")){
$this->bancoDados = mysqli_connect(SERVIDOR_BD, USUARIO_BD, SENHA_BD) or trigger_error(mysqli_error(),E_USER_ERROR);//3. Store in class variable
$this->database_bancoDados = BANCO_DE_DADOS;//4. Store in class variable
} else {
$this->bancoDados = mysqli_connect($servidor, $usuario, $senha) or trigger_error(mysqli_error(),E_USER_ERROR);//5. Store in class variable
$this->database_bancoDados = $bancoDeDados;//6. Store in class variable
}
}
}
class consultar {
var $bd;
var $res;
var $row;
var $nrw;
var $data;
function executa($sql=""){
if($sql==""){
$this->res = 0; // Pointer result of the executed query
$this->nrw = 0; // Line number the query returned, cruise control
$this->row = -1; // Array of the current query line
}
// Connects to the database
$this->bd = new conecta();//7. Store in class variable
$this->bd->conecta();//8. Store in class variable
mysqli_select_db($this->bd->bancoDados, BANCO_DE_DADOS);//9. Change Here For parameter sequence
$this->res = mysqli_query($this->bd->bancoDados, $sql); //10. Change here for parameter sequence
$this->nrw = #mysqli_num_rows($this->res);
$this->row = 0;
if($this->nrw > 0)
$this->dados();
}
function primeiro(){
$this->row = 0;
$this->dados();
}
function proximo(){
$this->row = ($this->row<($this->nrw - 1)) ?
++$this->row:($this->nrw - 1);
$this->dados();
}
function anterior(){
$this->row = ($this->row > 0) ? -- $this->row:0;
$this->dados();
}
function ultimo(){
$this->row = $this->nrw-1;
$this->dados();
}
function navega($linha){
if($linha>=0 AND $linha<$this->nrw){
$this->row = $linha;
$this->dados();
}
}
function dados(){
mysqli_data_seek($this->res, $this->row);
$this->data = mysqli_fetch_array($this->res);
}
}
$query = "INSERT INTO inserir(uname) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->bd->bancoDados);//11. Change Here for parameter
Related
I have a PHP script that is split into two separate PHP scripts (As they each serve a purpose and are quite lengthy). For simplicity let's call these 1.php and 2.php.
Script 1.php does an API call to a website passes the payload to a function. Once has truncated and inserted the new records into the table, it then includes the 2nd script. This is where the issue begins. Seemingly when I query the marketPlace table it returns a null array however if I insert a sleep(1) before I include 2.php it works! I can only summize that somehow the truncate and insert queries in 1.php had not completed before the next queries were called? (I've never come across this before!).
There is only one database connection and is defined by a database class which is contained in 1.php:
class Database
{
// This class allows us to access the database from any function with ease
// Just call it with Database::$conn
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
Global $servername;
Global $username;
Global $password;
Global $dbname;
try {
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli($servername, $username, $password, $dbname);
}
catch (exception $e) {
date('Y-m-d H:i:s',time()) . " Cant' connect to MySQL Database - re-trying" . PHP_EOL;
}
}
public static function checkDB()
{
if (!mysqli_ping(self::$conn)) {
self::$init = FALSE;
self::initialize();
}
}
}
The function that trunctated and inserted into the marketplace is:
function processMarketplace($marketData) {
// Decode to JSON
$outputj = json_decode($marketData, true);
$marketplaceCounter = 0;
// Check for success
if (($outputj['success']==true) && (!stristr($marketData, "error"))) {
// Create the blank multiple sql statement
$sql = "TRUNCATE marketplace;"; // Clears down the current marketPlace table ready for new INSERTS
//Loop through each multicall
foreach ($outputj['multiCall'] as $orderBook) {
foreach ($orderBook['marketplace'] as $orderLine) {
$type = $orderLine['type'];
$price = $orderLine['amountCurrency'];
// Add new SQL record (This ignores any duplicate values)
$sql .="INSERT IGNORE INTO marketplace (type, price) VALUES ('" . $type . "'," . $price . ");";
}
$marketplaceCounter++;
}
// Now run all the SQL's to update database table
if (strlen($sql) > 0) {
if (Database::$conn->multi_query($sql) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql . "<br>" . Database::$conn->error;
}
}
echo date('Y-m-d H:i:s',time()) . " == Marketplace Orderbook retreived == <BR><BR>" . PHP_EOL;
} else {
echo date('Y-m-d H:i:s',time()) . " Failed to get Marketplace data. Output was: " . $marketData . "<BR>" . PHP_EOL;
die();
}
}
I've chased this around for hours and hours and I really don't understand why adding the sleep(1) delay after I have called the processMarketplace() function helps. I've also tried merging 1.php and 2.php together as one script and this yields the same results. 2.php simply does a SELECT * FROM marketPlace query and this returns NULL unless i have the sleep(1).
Am I missing something easy or am I approaching this really badly?
I should add I'm using InnoDB tables.
This is how its called in 1.php:
$marketData = getData($user,$api); // Get Marketplace Data
processMarketplace($marketData); // Process marketplace data
sleep(1); // Bizzare sleep needed for the select statement that follows in 2.php to return non-null
include "2.php"; // Include 2nd script to do some select statements on marketPlace table
2.php contains the following call:
$typeArray = array('1','2','3');
foreach ($typeArray as $type) {
initialPopulate($type);
}
function initialPopulate($type) {
// Reset supplementary prices
mysqli_query(Database::$conn, "UPDATE marketPlace SET price_curr = '999999' WHERE type='" . $type . "'");
echo mysqli_error(Database::$conn);
// Get marketplace data <--- This is the one that is strangely returning Null (after the first loop) unless I place the sleep(1) before including 1.php
$query = "SELECT * FROM marketPlace WHERE type='" . $type . "'";
$result = mysqli_query(Database::$conn, $query);echo mysqli_error(Database::$conn);
$resultNumRows = mysqli_num_rows($result);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// Get information from the offertypes table
$query2 = "SELECT offerID FROM queryTypes WHERE type='" . $type . "'";
$result2 = mysqli_query(Database::$conn, $query2);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows2 = array();
while($r2 = mysqli_fetch_row($result2)) {
$rows2[] = $r2;
}
// Loop through marketplace data and apply data from the offertypes table
$sql1 = ""; // Create a blank SQL array that we will use to update the database
$i = 0;
foreach ($rows as $row) {
$sql1 .= "UPDATE marketPlace SET enrichmentType = " . $rows2[$i][0] . " WHERE type='" . $type . "';";
$i++;
}
// Now run all the SQL's to update database table
if (strlen($sql1) > 0) {
if (Database::$conn->multi_query($sql1) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql1 . "<br>" . Database::$conn->error;
}
}
}
You are using mysqli:multi_query.
Unlike query, multi_query does not retrieve the results immediately. Retrieving the results must be done using mysqli::use_result
An example from the documentation:
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
You don't need to print the results, but if you don't retrieve them, you are not guaranteed the INSERT has completed.
Note in the documentation for use_result at
https://www.php.net/manual/en/mysqli.use-result.php
it states
"Either this or the mysqli_store_result() function must be called
before the results of a query can be retrieved, and one or the other
must be called to prevent the next query on that database connection
from failing."
As a result of not calling store_result or use_result, you are having unpredictable results.
I want to count the amount of updates made on a record. The field name is pm_v. I got the following codes:
Update function:
function update_products_materials(){
$query = "UPDATE
" . $this->table_name . "
SET
pm_id = :pm_id1,
pm_code = :pm_code,
pm_name = :pm_name,
pm_department = :pm_department,
pm_temp = :pm_temp,
pm_color = :pm_color,
pm_v = pm_v +1
WHERE
pm_id = :pm_id2";
$stmt = $this->conn->prepare($query);
$this->pm_id=htmlspecialchars(strip_tags($this->pm_id));
$this->pm_code=htmlspecialchars(strip_tags($this->pm_code));
$this->pm_name=htmlspecialchars(strip_tags($this->pm_name));
$this->pm_department=htmlspecialchars(strip_tags($this->pm_department));
$this->pm_temp=htmlspecialchars(strip_tags($this->pm_temp));
$this->pm_color=htmlspecialchars(strip_tags($this->pm_color));
$stmt->bindParam(':pm_id1', $this->pm_id);
$stmt->bindParam(':pm_id2', $this->pm_id);
$stmt->bindParam(':pm_code', $this->pm_code);
$stmt->bindParam(':pm_name', $this->pm_name);
$stmt->bindParam(':pm_department', $this->pm_department);
$stmt->bindParam(':pm_temp', $this->pm_temp);
$stmt->bindParam(':pm_color', $this->pm_color);
$stmt->execute();
return $stmt;
}
This is the only place where I use pm_v.
The function is called in the following code:
$database = new Database();
$db = $database->getConnection();
// initialize objects
$products_materials = new Products_Materials($db);
$products_materials->id = $id;
$products_materials->view_products_materials();
$products_materials->update_products_materials();
if(isset($_POST["update"])){
$products_materials->pm_id=$id;
$products_materials->pm_code=$_POST['pm_code'];
$products_materials->pm_name=$_POST['pm_name'];
$products_materials->pm_department=$_POST['pm_department'];
$products_materials->pm_temp=isset($_POST['pm_temp']) ? $_POST['pm_temp'] : '';
$products_materials->pm_color=isset($_POST['pm_color']) ? $_POST['pm_color'] : '';
if($products_materials->update_products_materials() && (isset($_POST["update"]))){
header("Location: view_products_materials.php?id={$id}");
$_POST=array();
} else {
echo "<div class='alert alert-danger' role='alert'>Unable to save record.</div>";
}
}
Somehow, when I update a record it does +3 instead of +1. Can anyone explain why this is happening and how I can get it right?
I have splitted my php into 2/3 pieces using (MySQLi Procedural) :
First is dedicated to db (open,execute,Total Row, Affected Row,Close..)
Second is dedicated to other functionalities .
Here is an example :
db.php (First)
<?php
class DB {
var $DBUser = 'myuser';
var $DBPass = 'mypassword';
var $DBServer = 'localhost';
var $DBName = 'myDB';
var $con;
function __construct() {
$testcon = mysqli_connect($this->DBServer, $this->DBUser, $this->DBPass,$this->DBName);
if (!$testcon) {
die('Database connection failed: ' . mysqli_connect_error());
} else {
$this->con = $testcon;
}
}
function Qry($sql) {
if($result = mysqli_query($this->con,$sql) ) {
return $result;
}
else
{
$err = "Error: ".$sql. " :: ". mysqli_error;
die("$err");
}
}
function TotRows($result) {
if($result === false)
{
die("Error ".mysqli_error);
}
else return mysqli_num_rows($result);
}
function AffRows($result) {
return mysqli_affected_rows($result);
}
function LastRow($tblName) {
return mysqli_insert_id($this->con);
}
function close() {
mysqli_close($this->con);
}
}
?>
and
functions.php (Second)
public function GetBoolResult($db,$sql) {
$result=$db->Qry($sql);
$no_of_rows = $db->TotRows($db->con);
if ($no_of_rows > 0) {
// user exist
return true;
} else {
// user does not exist
return false;
}
}
When I try to execute the script I got the following Warning error :
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given in db.php
if you look at this function to get number of rows , the parameter is tested inside the function, the sql statement has been tested directly in the mysql serverwithout any error.
Any idea what's the problem ?
Don't you wan't to pass in the result, not the connection
$result = $db->Qry($sql);
$no_of_rows = $db->TotRows($result);
Got some code here. Been stuck on it for ages and I can't seem to get around the error.
<?PHP
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli = new mysqli('localhost', 'username', 'password', 'table');
$statsObjects = array();
$collatedObjects = array();
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Global $areRows;
$areRows = 2;
if( $result = $mysqli->query("SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT) )
{
while($row = $result->fetch_assoc())
{
array_push($statsObjects,
new Statistic(
$row['ID'],
$row['player_GUID'],
$row['shots_fired'],
$row['shots_hit'],
$row['damage_done'],
$row['damage_taken'],
$row['friendly_damage_done'],
$row['friendly_damage_taken']
));
}
$success = true;
} //end if
$result->free_result();
if($success)
{
foreach($statsObjects as $stat)
{
$statsGuid = $stat->getGuid();
$query = "SELECT COUNT(*) AS total FROM collatedStats WHERE player_GUID = '" . $statsGuid . "'";
if( $result2 = $mysqli->query($query, MYSQLI_USE_RESULT) )
{
$value = $result2->fetch_assoc();
$rows = $value['total'];
if($rows > 0)
{
$areRows = 1;
}
else
{
$areRows = 0;
}
}
else
{
echo("Error <br/>");
echo($mysqli->error);
}
if($areRows == 1)
{
echo("Found a row! <br/>");
}
elseif($areRows == 0)
{
Echo("No rows found. =) <br/>");
}
} //end foreach
}
//OBJECT
class Statistic
{
var $GUID;
var $shotsfired;
var $shotshit;
var $damagedone;
var $damagetaken;
var $friendlydamagedone;
var $friendlydamagetaken;
var $ID;
function Statistic($ID, $GUID, $fired, $hit, $ddone, $dtaken, $fddone, $fdtaken)
{
$this->id = $ID;
$this->GUID = $GUID;
$this->shotsfired = $fired;
$this->shotshit = $hit;
$this->damagedone = $ddone;
$this->damagetake = $dtaken;
$this->friendlydamagedone = $fddone;
$this->friendlydamagetaken = $fdtaken;
}
function getID()
{
return $this->ID;
}
function getGuid()
{
return $this->GUID;
}
function getShotsFired()
{
return $this->shotsfired;
}
function getShotsHit()
{
return $this->shotshit;
}
function getDamageDone()
{
return $this->damagedone;
}
function getDamageTaken()
{
return $this->damagetaken;
}
function getFriendlyDDone()
{
return $this->friendlydamagedone;
}
function getFriendlyDTaken()
{
return $this->friendlydamagetaken;
}
function getAccuracy()
{
if($shotsfired == 0)
{
$accuracy = 0;
}
else
{
$accuracydec = $shotshit / $shotsfired;
$accuracy = $accuracydec * 100;
}
return $accuracy;
}
}
Basically every time i run the code, it keeps coming up with the error "Commands out of sync; you can't run this command now". I've spent 2 days trying to fix it - following peoples instructions about freeing the result before running the next one. I even used a prepared statement in previous code however it didn't work either - this is newly written code in an attempt to get it working. All the reading i've done suggests that this error happens when you try to run an sql command while another one is still receiving data - however i've called my first query, stored it all in an array - and then i'm looping through the array to get the next lot of data..and that's giving me an error, which is where i'm getting confused.
Any help would be appreciated!
Thank You to #andrewsi for his help - it turns out that having the MYSQLI_USE_RESULT inside SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT was giving me the error. Removing that allowed me to do my code normally.
Hopefully this helps others that may have the same problem. =)
So i'm working on a project and i am running to to a few mysql & php errors.
First Error :
This is all code associated with First Error
// Database Class
class Database {
public $_link, $_result, $_numRows;
public function __construct($server, $username, $password, $db){
$this->_link = mysql_connect($server, $username, $password) or die('Cannot Execute:'. mysql_error());
mysql_select_db($db, $this->_link);
}
public function disconnect(){
mysql_close($this->_link);
}
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result);
}
public function numRows() {
return $this->_numRows;
}
public function rows(){
$rows = array();
for($x = 0; $x < $this->numRows(); $x++) {
$rows[] = mysql_fetch_assoc($this->_result);
}
return $rows;
}
}
// Setup.php
$is_set = 'false';
global $company_name, $ebay_id;
if( isset($_POST['ebay_id'], $_POST['company_name']) ){
$_ebay_id = $_POST['ebay_id'];
$_company_name = $_POST['company_name'];
$is_set = 'true';
} else {
// Silence is Golden!
}
$_service_database = new Database('localhost', 'root', 'password', 'chat-admin');
$_service_database->query("SELECT * FROM installs WHERE `identity` = '$mysqldb' AND `db_name` = '$mysqldb'");
if ($_service_database->numRows() == 0){
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
} else {
// header("Location: index.php");
}
$_service_database->disconnect();
?>
<form name="setup" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input placeholder="eBay Username" type="text" name="ebay_id">
<input placeholder="Company Name" type="text" name="company_name">
<input type="hidden" name="insert" value="true">
<input type="submit">
</form>
So what this does is checks if the variables defined are in the database if they are not then when the form is submitted it inserts our values, if they are in the database it redirects to index.php, ok so i am receiving the all mighty MySQL num_rows* expects parameter 1 to be resource, boolean given ..., now i have searched everywhere and only found that the die error should solve, that is why you can see it on line 16 in the function query, now although i get the error everything still works its not really good for me to turn error reporting off so any help would be great. Also if you see undefined variables like $mysqldb they are actually set but on a different page and they are valid
Second Error : = function made for simplicity of a templating system
This is all associated with Second Error
function get_content_type($value){
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}
if($value == $title[1]){
echo '<title>'.$value.'</title>';
} else if ($value == $css[1]) {
echo '<link rel="stylesheet" href="'.$value.'">';
} else if ($value == $javascript[1]) {
echo '<script src="'.$value.'"></script>';
}
}
// Calling
get_content_type('title: Welcome to my site');
get_content_type('css: http://something.com/style.css');
get_content_type('js: http://code.jquery.com/jquery-latest.min.js');
everything works as this outputs
<title>Welcome to my site</title><link rel="stylesheet" href="http://somesite.com/style.css"><script src="http://code.jquery.com/jquery-latest.min.js"></script>
Only when i set error_reporting(0);
The errors i get are undefined variables because obviously i'm setting one, then im unsettling that one and setting the other so eventually only 1 is true although its already outputted all of them correctly.
UPDATE
Second Error : Errors =
Notice: Undefined variable: css in C:\Server\www\hidie\libs\test.php on line 19
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
Notice: Undefined variable: title in C:\Server\www\hidie\libs\test.php on line 17
First Error : Errors =
ERROR: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Ok so here's your problem:
First, as mentioned in the comment, mysql_num_rows only works on select and show. You have it in your query method, which is called by an insert. You can't do that.
public function query($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
$this->_numRows = mysql_num_rows($this->_result); // <- BAD!
}
You call it on this line:
if($is_set == true){
$_service_database->query("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
You could make a second method for database and call it for all calls that write to the db:
public function execute($sql){
$this->_result = mysql_query($sql, $this->_link) or die('Cannot Execute:'. mysql_error());
}
which would be called like so:
if($is_set == true){
$_service_database->execute("INSERT INTO installs (ebay_id, name, db_name, identity) VALUES ('$_ebay_id', '$_company_name', '$mysqldb', '$mysqldb')");
}
Second, you need to implicitly define the variables $css and $title outside of those conditionals. Otherwise you are attempting to call undefined vars as indicated by the message...
$title = "";
$css = "";
if (strpos($value,'title:') === 0 ) {
$title = explode("title: ",$value);
$value = $title[1];
} else if (strpos($value,'css:') === 0 ) {
$css = explode("css: ",$value);
$value = $css[1];
} else if (strpos($value, 'js:') === 0 ) {
$javascript = explode("js: ", $value);
$value = $javascript[1];
} else {
// Silence is Golden
}