Why is this not inserting into mysqli database? - php

So I can not figure out why this is not adding the content to the DB. I need to add the itemcode and item into the database then be able to read it. This is what i have:
add.php
include('dbconnect.php');
function get_posts() {
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
mysqli_close($con);
dbconnect.php
$con = mysqli_connect("localhost","root","root","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Connected to Database. Please Continue.";
}
Is anyone able to help?? This is weird to me that it is not working.

It looks like you are calling your insert query from inside of a function yet $con is in the global scope. To include $con within your function you must do this:
include('dbconnect.php');
function get_posts() {
global $con;
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
get_posts(); // you can call get_posts() here
mysqli_close($con);
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
And, be sure to call your function, it is as simple as typing the following:
get_posts();

Related

php function with mysqli

This is my fonction.php :
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
But it does not works with my code when I want to call this function :
<?php
include("fonctions.php");
?>
<html>
<form name="inscription" method="post" action="form.php">
xxx : <input type="text" name="xxx"/> <br/>
xxx: <input type="text" name="xxx"<br/>
<input type="submit" name="valider" value="OK"/>
</form>
<?php
if (isset ($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
connect();
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
}
?>
</body>
</html>
Before I was using mysql_connect and it was more simple, my fonction was like this :
<?php
function connect(){
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('MaBase', $base) ;
}
?>
What is the best way to create a good include with my mysql params ? THanks all for any help.
Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...
You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.
function connect($sql){
For defining it, and then to call it
$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);
You'll also need your function to return some sort of value.
What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)
This is written once, and require_once()'d all across 15 web apps for the college I work at.
To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff
database.class.php
//databaseconnection
class DatabaseConnections{
function connect($databaseNaem){
try{
return $connection=mysqli_connect("localhost","user","password",'database');
}catch(Exception $e){
echo 'Message:'.$e->getMessage();
}
}
function CloseConnection($dataObject){
if(mysqli_close($dataObject)){
return 1;
}else{
echo "coudn't Close the Database Connection";
}
}
function convert($connection , $vari){
return mysqli_real_escape_string($connection,$vari);
}
}
//queryclass
class Query{
function queryNoresult($stmt){
if($stmt->execute()){
return 1;
}
}
function queryNumOfRows($stmt){
$stmt->execute();
$result = $stmt->get_result();
return mysqli_num_rows($result);
}
function QueryResult($stmt){
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
function illcallothers($stmt,$callto){
if($callto == 1){
return $this->queryNoresult($stmt);
}if ($callto==2) {
return $this->queryNumOfRows($stmt);
}
if($callto == 3){
return $this->QueryResult($stmt);
}
}
}
as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters
Created statement
The function number
there 3 option in this
if you call $query->illcallothers($stmt,1) this call the function
only for execute best for delete and insert because it's return 1 if
it's success
if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while
if you call $query->illcallothers($stmt,3) this will return result set from your query
Now lets go to your problem execution
//first you have to require the database file
require_once('database.class.php');
//Then you have to create object from them
$mymainObj = new DatabaseConnections();//obj from database
$connetion = $mymainObj->connect('databasename');//this will return a connection Object
$stmt = $connection->stmt_init(); //then the statement you need the connection object to this
$query = new Query();//object from the query class
//i am not going to put form part in here it will get messy
$titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection
$auteur=$mymainObj->convert($connection,$_POST['xxx']);
//now you have create the sql
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$author);
if($query->illcallothers($stmt,1)){
echo "Query Success";
}
}
It should be,
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
?>
Your query should be,
<?php
if (isset($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
$connection = connect();
if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);
if($result){
echo "done";
}else{
echo "faild";
}
}
}
?>
You should take a tour/learn the basics of OOP
It seems like all the above answers missed that you have two variables with the same name:
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
Both are called $xxx
IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)

I wanted to take datas from database and also change the query dynamically and store the id from database in an array and use then to call a function

I am new to PHP, can anyone help me out in this. What I am trying to do is call a function which fetch id from a table and store id in an array, then calling another method in a loop in such a way that the array elements should be parameter which is passing in function.
<?php
include 'connection.php';
$releaseidarr=array();
function getreleaseid($p)
{
$releaseid=array();
$releaseidp="select release_id from `release` where project_id=".$p.";";
$query4=mysql_query($GLOBALS['db'],$releaseidp);
while($row=mysqli_fetch_array($query4))
{
$releaseid[]=$row['release_id'];
}
return $releaseid;
}
$p=1;
while($p<8)
{
//echo "hi";
$releaseidarr=getreleaseid($p);
echo $releaseidarr[$p];
$p++;
}
?>
Connection.php contains
<?php
$GLOBALS['server']="******";
$GLOBALS['username']="*****";
$GLOBALS['password']="****";
$GLOBALS['database']="dashtest";
$GLOBALS['conn']= mysqli_connect($server,$username,$password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$GLOBALS['db'] = mysqli_connect($server,$username,$password,$database);
//echo "connected";
?>
Here Don't use both mysql and mysqli. Only use to write in mysqli.
and in foreach loop use array push method. first declare one empty array like
$array = [];
foreach($a as $k){
array_push($array,$k);
}
return $array;

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

PHP MySQL trouble

If I run this code , the value in the SQL base is added 5x.
Code:
function token($u) {
include('../config.php');
$token=md5(rand()+$u);
$date = date('Y-m-d H:i:s');
$tokenQuery = 'INSERT INTO '.$prefix.'tokens(`token`, `user`, `date`) VALUES ("'.$token.'","'.$u.'","'.$date.'")';
$mysqli->query($tokenQuery);
}
token ('filips');
See how it look my SQL base
My config is:
$host = 'my server';
$user = 'my username';
$pass = 'my password';
$data = 'pn_16734995_filipcms_demo';
$prefix = 'fc_';
$mysqli = new mysqli($host,$user,$pass, $data);
$mysqli->query("SET NAMES 'utf8'" );
if ($mysqli->connect_errno) {
echo "Server not working: (" . $mysqli->connect_errnor. ") " . $mysqli->connect_error;
}
Nothing in your code will make the INSERT statement happen 5 times. However, if you echo "function called"; inside of your function, you can see if the function is being called 5 times, then you can figure out where up the line your function is being called 5 times.
you don't need to include the whole file just pass $mysqli as a parameter or put it in a global scope;
function token($u,$mysqli) {
}
OR
function token($u) {
global $mysqli;
}

accessing connection variable in a while loop

I am trying to acces my connection variable while I run a while loop, yet when I try to call a function, it bogus out on me and PHP gives me the so called boolean error when I try to prepare my statement within the function.
I debugged it to the point that I know my variable $CategorieId is being pushed on and I do get a array return of $con when I do a print_r in the function itself. However when I try to acces it when I prepare my statement, it just returns me a boolean, thus creating the error in the dropdown, not being able to fill it up.
The setup is as followed.
dbControl.php
$con = mysqli_connect('localhost','root','','jellysite') or die("Error " . mysqli_error($con));
function OpenConnection(){
global $con;
if (!$con){
die('Er kan geen verbinding met de server of met de database worden gemaakt!');
}
}
functionControl.php
function dropdownBlogtypeFilledin($con,$CategorieId){
echo "<select name='categorie' class='dropdown form-control'>";
$sql = "SELECT categorieId, categorieNaam
FROM categorie";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$categorieId,$categorieNaam);
while (mysqli_stmt_fetch($stmt1)){
echo "<option value='".$categorieId."'.";
if( $categorieId == $CategorieId){
echo "selected='selected'";
}
echo ">".$categorieNaam."</option>";
}
echo "</select>";
}
Blogedit.php
<?php
require_once '../db/dbControl.php';
require_once '../db/functionControl.php';
session_start();
OpenConnection();
$id = $_SESSION['user'];
?>
// some html up to the while loop
<?php
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
?>
// again some HTML
<?php dropdownBlogtypeFilledIn($con,$CategorieId); ?>
// guess what, more html!
<?php
}
?>
Does anyone know how I can solve it? I tried it with the global variable (the OpenConnection() function) but it didn't seem to work.
Edit
I confirm it has indeed to do with the $con variable. I tested it by defining the $con variable again in the function, and it printed perfectly what I wanted. Its a bad solutions. I just prefer to have it defined once.
The weird thing is that it happens only when i put it in a while loop. I have a create form which is exactly the same, except there is no while loop, since I create it all from scratch and there is no PHP involved on that part. I have there a dropdown function as well, which also requires the $con variable, but there it works. I really think it has to do with the while loop.
I solved it for now by creating a new instance of the connection variable before i initiated the prepared statement of the page retrieving the information.
<?php
$connection = $con;
$a = $_GET['a'];
$sql = "SELECT blog.blogId,
blog.blogTitel,
blog.blogCategorieId,
blog.blogSynopsis,
blog.blogInhoud
FROM blog
WHERE blog.blogId = ? ";
mysqli_stmt_init($con);
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt1,'i',$a);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1, $blogId, $Titel, $CategorieId, $Synopsis, $Inhoud );
mysqli_stmt_store_result($stmt1);
while (mysqli_stmt_fetch($stmt1)){
$Synopsis = str_replace('\r\n','', $Synopsis);
$Inhoud = str_replace('\r\n','', $Inhoud);
<?php dropdownBlogtypeFilledIn($connection ,$CategorieId); ?>
?>
With the variable $connection I could initiate the function that required the connection details within the while call. I am not sure if there is a cleaner option here, but indeed I read somewhere that I couldn't use the same connection variable if I am already using it in a prepared statement. Appearantly I cannot ride this one the same connection variable, and that seemed to be the problem. I will look into this and hope I dont have to write a while bunch of connection variables whenever I have multiple dropdowns for example that pull information from the database.

Categories