I need to fetch "UID" row data from db_tags where "Contador" is selected, then insert it into db_rfid. I've tried the fetch commands, but doens't seems to work.
require_once "config.php";
require_once "session.php";
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])){
$contador = trim($_POST['Contador']);
$nome = trim($_POST['nome']);
if($query = $db->prepare("SELECT * FROM db_tags.tags2 WHERE CONTADOR = ?")){
$query->bind_param('s', $contador);
$query->execute();
$query->store_result();
$insertQuery = $db->prepare("INSERT INTO db_rfid.tbl_rfid (UID, Nome) VALUES (?,?)");
$insertQuery->bind_param("ss", $uid, $nome);
$result = $insertQuery->execute();
header("inserir.php");
$insertQuery->close();
$query->close();
exit;
}
}
mysqli_close($db);
?>
because a default database is selected in your config.php file.
$db=PDO("...;dbname=XXXX;...");
For this you need to create 2 PDO objects
$dbConnection1=PDO("...;dbname=db_tags;...");
$dbConnection2=PDO("...;dbname=db_rfid;...");
usage:
$query1 = $dbConnection1->prepare("SELECT * FROM tags2 ...");
$query1->execute(...)
$query2= $dbConnection2->prepare("INSERT INTO tbl_rfid ...");
$query1->execute(...)
Related
I am beginning to create my own Interface to use with MySql though I cannot seem to create a database with the code I have at the bottom. Everything else works also i can echo out the $ObtainDatabase variable to see that it does have a value stored. Any suggestions would be great.
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>
Can you try this Code.
Details about this error can be found in the mysql docs. Reading those details makes it clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
Here is the doc where you can refer
<?php
session_start();
//define connection
$conn = new mysqli('localhost', 'over_watch','XXXXXXx','billing');
//Variables
$UserEmail = $_SESSION['email'];
$MysqlUserDataBaseCreate = $_POST['create_database'];
//CheckIfUserExists
$SeeIfUserExist = $conn->prepare("SELECT (email) FROM database_users WHERE email= ?;");
$SeeIfUserExist->bind_param('s',$UserEmail);
$SeeIfUserExist->execute();
$SeeIfUserExist->store_result();
$SeeIfUserExist->bind_result($ObtainedEmail);
$SeeIfUserExist->store_result();
$SeeIfUserExist->fetch();
$RowsReturnedFromPreparedStatment = $SeeIfUserExist->num_rows();
if($RowsReturnedFromPreparedStatment < 1){
$InsertIntoDatabase = $conn->prepare("INSERT INTO database_users(email,check_if_created) VALUES(?,?);");
$InsertIntoDatabase->bind_param('ss',$UserEmail,$MysqlUserDataBaseCreate);
$InsertIntoDatabase->execute();
$InsertIntoDatabase->store_result();
$SelectDatabaseToCreate = $conn->prepare(" SELECT (check_if_created) FROM database_users WHERE email = ?;");
$SelectDatabaseToCreate->bind_param('s', $UserEmail);
$SelectDatabaseToCreate->execute();
$SelectDatabaseToCreate->store_result();
$SelectDatabaseToCreate->bind_result($ObtainDatabase);
$SelectDatabaseToCreate->fetch();
$CreateDatabase = "CREATE DATABASE $ObtainDatabase ;";
$conn->query($CreateDatabase);
}else{
echo 'user permitted to one database';
}
?>
I've got a problem in my PHP code whith an SQL statement.
I want to get back the ID of my Indice where my name = 'myname'.
Here is my code :
<?php
include 'Connection.php';
try {
$db = new PDO("$server:host=$host;dbname=$base", $user, $passwd);
//Statement = INSERT INTO indice
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name);
$stmtInd->bindParam(':IDFormation', $idformation);
//Statement = INSERT INTO note
$stmtNote = $db->prepare("INSERT INTO note(ID, Valeur, Valeurtext, IDIndice)
VALUES (:ID, :Valeur, :Valeurtext, :IDIndice)");
$stmtNote->bindParam(':ID', $ID);
$stmtNote->bindParam(':Valeur', $valeur);
$stmtNote->bindParam(':Valeurtext', $valeurtext);
$stmtNote->bindParam(':IDIndice', $IDindice);
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();
$resultat = $noteIdindice->fetch(\PDO::FETCH_ASSOC);
var_dump($resultat);
//Indice 1
$name = "Equilibre theorie / pratique";
$idformation = "1";
$stmtInd->execute();
$valeur = $_POST["indice1"];
$valeurtext = "";
$IDindice = $resultat['ID'];
$stmtNote->execute();
echo "Success";
}
catch (PDOException $e) {
die("Impossible de se connecter a la source de donnees...");
}
?>
There is other Indice but you dont need it cuz its the same as "//Indice 1".
Everything works and i have no failure. But my query give me a wrong return. It returns me "0" instead of the ID i want.
Do you guys know why ?
Your prepared statement is never executed, you should add execute :
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();//Add this row
$resultat = $noteIdindice->fetch();
EDIT :
You are trying to binding params with null values.
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name); //$name variable not exists
$stmtInd->bindParam(':IDFormation', $idformation);//$idformation variable not exists
Try to do this :
<?php
include 'Connection.php';
try {
$db = new PDO("$server:host=$host;dbname=$base", $user, $passwd);
//Indice 1
$name = "Equilibre theorie / pratique";
$idformation = "1";
$valeur = $_POST["indice1"];
$valeurtext = "";
//Statement = INSERT INTO indice
$stmtInd = $db->prepare("INSERT INTO indice(ID, Name, IDFormation)
VALUES (:ID, :Name, :IDFormation)");
$stmtInd->bindParam(':ID', $id);
$stmtInd->bindParam(':Name', $name);
$stmtInd->bindParam(':IDFormation', $idformation);
$stmtInd->execute();
//Statement = INSERT INTO note
$stmtNote = $db->prepare("INSERT INTO note(ID, Valeur, Valeurtext, IDIndice)
VALUES (:ID, :Valeur, :Valeurtext, :IDIndice)");
$stmtNote->bindParam(':ID', $ID);
$stmtNote->bindParam(':Valeur', $valeur);
$stmtNote->bindParam(':Valeurtext', $valeurtext);
$stmtNote->bindParam(':IDIndice', $IDindice);
$stmtNote->execute();
$noteIdindice = $db->prepare("SELECT ID FROM indice WHERE Name = :Name");
$noteIdindice->bindParam(':Name', $name);
$noteIdindice->execute();
$resultat = $noteIdindice->fetch(\PDO::FETCH_ASSOC);
var_dump($resultat);
$IDindice = $resultat['ID'];
echo "Success";
}
catch (PDOException $e) {
die("Impossible de se connecter a la source de donnees...");
}
?>
The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this
I insert data into a table called 'roster'. The first column (id_roster) is an id using mysql auto-increment.
I run a SELECT to find the id_roster
I use this id_roster to insert it into a table 'roster_par_membre' along with other data
if ($insert_stmt = $mysqli->prepare("INSERT INTO `roster`(`nom_roster`, `description_roster`, `id_organisation`, `created_by`, `creation_date`,`modified_by`) VALUES (?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssiisi', $roster_name, $description_roster, $organisation_id, $user_id, $creation_date, $user_id);
if (!$insert_stmt->execute()) {
$reponse = 'Sorry, a database error occurred; please try later';
} else {
// if INSERT OK -> create a new line in roster_membre table
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
$level = 1;
//2. create a line with the roster_id and insert the membre as level 1
$insert_stmt = $mysqli->prepare("INSERT INTO `roster_par_membre`(`id_membre`, `id_roster`, `level`, `modified_by`) VALUES (?,?,?,?)");
$insert_stmt->bind_param('iiii', $user_id, $id_roster, $level, $user_id);
$insert_stmt->execute();
$reponse = 'success';
}
So far the code is working but it is not very nice.
Is there a way when we create a new line in a table to directly return a value (id with auto-increment) to be used in a sql query (to insert data into a second table)? or maybe to merge the two query (the two INSERT) in one statment?
short edit: it is an AJAX $response the return value (JSON)
Ok,solution:
//1. get the roster_id
$sql = "SELECT r.id_roster
FROM roster r
WHERE r.nom_roster = ?
LIMIT 1";
$stmt = $mysqli->prepare($sql);
if ($stmt) {
$stmt->bind_param('s', $roster_name);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($id_roster);
$stmt->fetch();
Just need to replace all this part by
$id_roster = $mysqli->insert_id;
nice and easy. THANKS to albanx
these are the functions I used for query on projects that I do not want to use any framework (just php):
/**
*
* Executes query methods
* #param string $query the query string
* #param array $vals array of values
* #param bool $show show the query
* #return int/array/false
*/
function q($query, $vals=array(), $show_query=false)
{
$conn = new mysqli(...)
$offset = 0;
foreach ($vals as $v)
{
$cv = $conn->real_escape_string($v);//escape the value for avoiding sql injection
$fv = ($v===NULL) ? 'NULL':"'".$cv."'"; //if value is null then insert NULL in db
$qpos = strpos($query, '?', $offset);//replace the ? with the valeue
$query = substr($query, 0, $qpos).$fv.substr($query, $qpos+1);
$offset = $qpos+strlen($cv)+1;
}
$result = $conn->query($query);
if($show || $result===false) echo $query."<br>";
$rows = array();
if($result===true)
{
return $conn->affected_rows;
}
else if($result===false)
{
return false;
}
else
{
while ($row = $result->fetch_array(MYSQLI_ASSOC) )
{
$rows[]=$row;
}
}
return $rows;
}
function lastid()
{
return $this->qval("SELECT LAST_INSERT_ID()");
}
Usage example:
q('INSERT INTO USER(name, email) VALUES(?,?)', array('admin','admin#admin.com'));
$id = lastid();
I'm new to PHP,I got error in my web page.It said:
Notice: Undefined index: itemid in /home/tz005/public_html/COMP1687/edit.php on line 103
Can I use isset to fix this problem? If yes, how to do so? Here is my script:
<?php
//include database connection
include 'dbconnect.php';
// if the form was submitted/posted, update the item
if($_POST){
//write query
$sql = "UPDATE
item_information
SET
itemtitle = ?,
itemdescription = ?,
date = ?,
WHERE
itemid= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(
'sssi',
$_POST['itemtitle'],
$_POST['itemdescription'],
$_POST['date'],
$_POST['itemid']
);
// execute the update statement
if($stmt->execute()){
echo "Item was updated.";
// close the prepared statement
$stmt->close();
}else{
die("Unable to update.");
}
}
$sql = "SELECT
itemid, itemtitle, itemdescription, date
FROM
item_information
WHERE
id = \"" . $mysqli->real_escape_string($_GET['itemid']) . "\"
LIMIT
0,1";
// execute the sql query
$result = $mysqli->query( $sql );
//get the result
if ($result = $mysqli->query( $sql )) {
if ($row = $result->fetch_assoc()) {
// $row contains data
}
}
//disconnect from database
$result->free();
$mysqli->close();
?>
change
$mysqli->real_escape_string($_GET['itemid'])
to
$mysqli->real_escape_string($_POST['itemid'])
or use empty() or isset() to check values exist
Yes you can do it with isset() function
Create conditions for it
if(isset($_GET['itemid'])){
//execute your code
}
else{
//header them back to page or show error that itemid not set or something else whatever suits you
}