using "INSERT INTO" statement in php code doesn't work - php

I'm trying to build a database for a bookstore with 3 tables: Book, Volume and Publication. I'm using mysqli() and the code neither works nor echoes any errors.
<?php
//connect to db
$conn = new mysqli("localhost", "root", "", "ershadbookstore");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
#new recoed: if the new record is inserted into book successfully, another new record is inserted into volume table. the same goes for volume and phblication table. at the end the total number of this volumn is editted in the rows with the same isbn.
$sql = "INSERT INTO Book (name, vnum, writer, translator, publisher, genre, format)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$last_bid = $conn->insert_id;
$sql = "INSERT INTO Volume (isbn, bid, vnum, note, image)
VALUES ('test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO Publication (isbn, pubnum, pyear, circulation, fpyear, pnum, price, num)
VALUES ('test', 'test', 'test', 'test', 'test', 'test', 'test', 'test')";
if ($conn->query($sql) === TRUE) {
$sql= "SELECT SUM(num) FROM Publication
WHERE (isbn='test')";
if ($conn->query($sql) === TRUE) {
$totalNum=$conn->query($sql);
$sql1= "UPDATE Volume
SET (tnum = test)
WHERE (isbn= test)";
if ($conn->query($sql1) === TRUE)
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
}
else{
return "Error publication table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for volume table: " . $sql . "<br>" . $conn->error;
}
}
else {
return "Error for book table: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

The problem is that you are checking with === TRUE.
As PHP Manual says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
While your error checking would work for INSERT or UPDATE queries the SELECT query will not return true. In fact checking like this for boolean values is completely unnecessary.
Remove the check for === TRUE and your code should work fine.
$sql= "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
if ($conn->query($sql)) { // removed === TRUE
$sql1= "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
if ($conn->query($sql1))
{
echo "true";
}
else
{
return "Error publication table: " . $sql1 . "<br>" . $conn->error;
}
}
If you enable mysqli error reporting, you don't need any if statements, which will make your code much simpler:
$sql = "SELECT SUM(num) FROM Publication
WHERE isbn='test'";
$conn->query($sql);
$sql1 = "UPDATE Volume
SET tnum = 'test'
WHERE isbn= 'test'";
$conn->query($sql1);
echo "true";
In addition, your values in the last update queries are missing quotes.
SET (tnum = 'test')
WHERE (isbn= 'test')";
Also there is no need to execute your SELECT query twice to get the values. You should refactor your code so that the second query ($totalNum=$conn->query($sql);) is not needed.

Also remove the triple equals === you are not comparing so you don not need a comparison operator so instead use !== FALSE
Example
if ($conn->query($sql) !== FALSE)
so this is saying if its not FALSE, than its TRUE so it will continue to run.

Related

Populate and rank a table using RANK() function using PHP and SQL statements

I'm working with this MariaDB database:
Server version: 10.3.31-MariaDB-log-cll-lve - MariaDB Server
Protocol version: 10
I would like to update and rank a table whenever users submit a form.
This first part of code work properly, inserting the user entries when he submits the form (I check connection on run and I also checked the database and it is filled) .
At this point the record has been created.
(from //---RANKING PART------------- in the code)
Now I need to rank the table, so I tried to use RANK() function as reported in https://mariadb.com/kb/en/rank/
I tried a lot but it doesn't work
add_action( 'gform_after_submission_13', 'myfunction', 10 , 1); // execute myfunction when user submit form 13
function myfunction($entry){
$nome = rgar( $entry, '1' );
$categoria = rgar( $entry, '4' );
$score = rgar( $entry, '2' );
$ig = rgar( $entry, '3' );
$servername = "xxxxxxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxxxxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Table1 (nome, categoria, score, ig)
VALUES ('$nome','$categoria','$score','$ig')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//---RANKING PART-------------
$sql2="SELECT
RANK() OVER (PARTITION BY categoria ORDER BY score DESC) AS myrank,
nome, categoria, score, ig
FROM Table1 ORDER BY nome, score DESC";
if ($conn->query($sql2) === TRUE) {
echo "Ranking update";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
When I try to do a testing submission on the top of the browser I read
New record created successfullyError: INSERT INTO Table1 (nome,
categoria, score, ig) VALUES ('testname','test
category','576','test_ig')
P.S. I don't know if it useful to know that I putted this code in snippet plugin of wordpress (plugin to create a php snippet). I tested the plugin with others code and it works properly.

Codeigniter XML Datafeed to Multiple (MYSQL Tables)

goodness.. it's been a quite a headache for me.
I'm trying to get variable SQL1, SQL2 and SQL3 to update different mysql tables.. but how on earth will SQL2 and SQL3's "product_id" fields, correlate with SQL1?
See 'id' in the insert sections in SQL2 and SQL3.. i'm not sure how to replace and grab this generated data into this sections without making more ugly code.
Also, if any of you have any idea how to make this easier, please help a fellow out here.. this looks pretty dirty to me.. surely there are better ways :(
// DB Settings
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Load data from XML file
$xml = simplexml_load_file("Datafeed.xml");
// Capture XML Data
foreach($xml->children() as $product) {
// Change stock wording
$stock = $product->stock;
if ($stock == 'yes') {
$stock = 'on';
} else {
$stock = 'off'; }
// Convert XML data and insert into MYSQL
$sql = "INSERT INTO testshop_products (product_id, product_name, product_type, product_price, product_status) VALUES ("echo $product->code;", "echo $product->cat;", "echo $product->price;","echo $stock;")";
$sql2 = "INSERT INTO testshop_product_details (product_id, product_color, product_image, details_status) VALUES ('id', "Generating...", "echo $product->img;","echo $stock;")";
$sql3 = "INSERT INTO testshop_spesifications (product_id, specs_meta, specs_details, specs_slug, specs_status) VALUES ('id', General, "echo $product->img;", general, "echo $stock;")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
write store procedure and inset all records and all table it will find.
store procedure like this
CREATE PROCEDURE `addJobApplicant`(IN XMLINPUT
text, OUT vresult VARCHAR(100))
BEGIN
DECLARE iCounter INT DEFAULT 1;
DECLARE maxCount INT;
SET vcompID=ExtractValue(XMLINPUT, '/ROOT/HEADER/COMPANYID[$iCounter]');
SET vjpID=ExtractValue(XMLINPUT, '/ROOT/HEADER/JOBID[$iCounter]');
insert command here
SET vresult = 'Successfully Inserted';
end

Sql query not running in php and maybe an issue related to sql

Function is running properly and my other query of inserting data is also running perfectly which is commented below.
This is the error i am getting "Error: SELECT MAX(product_id) FROM product_attribute "
public function add_tbl1($attribute_id , $attribute_description){
$con=$this->con;
$id = mysqli_real_escape_string($con, $attribute_id);
$description = mysqli_real_escape_string($con, $attribute_description);
$sql2="SELECT MAX(product_id) FROM product_attribute ";
$no=0;
if ($con->query($sql2) === TRUE) {
$no= $con->query($sql2);
$no=$no+1;
echo $no;
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
}
/*$sql = "INSERT INTO product_attribute ( attribute_id, attribute_description)
VALUES ( '$id', '$description')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
} */
}
if $con is a mysqli-connection, then $con->query with a SELECT will never return true.
it will either return false or a resource.
you should rather check with
$con->query($sql2) !== false))
From http://php.net/manual/en/mysqli.query.php
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
$con->query($sql2) === TRUE
mysqli::query does not return TRUE on success for SELECT statements. It returns
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object
So change your if condition accordingly.
$sql2="SELECT MAX(product_id) as id FROM product_attribute ";
if ($result = $con->query($sql2)) {
$row = $result->fetch_assoc();
$id = $row["id"];
}

Insert and Update on one click

I have two table Billing_month and registration in mysql. i want to insert into Billing_month and at the same time i want to update a row (Arrears) in registration table. how can i do this.
PHP Code is:
<?php
//create connection
include("database/db.php");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Insert Data
#$month=$_POST['Bill_month'];
#$issuedate=$_POST['Bill_issue_date'];
#$duedate=$_POST['Bill_due_date'];
#$surcharge =$_POST['Surcharge'];
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge) values('$month','$issuedate','$duedate','$surcharge')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Need your help?
I would only run the query update if the insert was successful.
<?php
//create connection
include("database/db.php");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Insert Data
#$month=$_POST['Bill_month'];
#$issuedate=$_POST['Bill_issue_date'];
#$duedate=$_POST['Bill_due_date'];
#$surcharge =$_POST['Surcharge'];
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge)
values('$month','$issuedate','$duedate','$surcharge')";
if(mysqli_query($link, $sql)){
$res = "Records added successfully.";
// Update Registration Arrears query
$sql_upadte = "Update registration ...."
if(mysqli_query($link, $sql_update)){
$res .= "<br>Registration record updated successfully.";
}else{
$res .= "<br>ERROR: Could not able to execute.<br>".$sql_update."<br>".mysqli_error($link);
}
echo($res);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Use two queries to insert and to update, then execute them
$sql = "INSERT INTO billing_month (Bill_month,Bill_issue_date,Bill_due_date,Surcharge)
values('$month','$issuedate','$duedate','$surcharge')";
$sqlUpdate = "Place your update query here";
$insert = mysqli_query($sql);
$update = mysqli_query($sqlUpdate);
After insert into your billing table get last inserted id
$id = mysql_insert_id();
Then update your registration table.
$query = "UPDATE registration SET .... WHERE billing_id = $id; ";
mysql_query($query);
This is a simple multi query, you can look at php - multi_query here.
<?php
$query = "INSERT INTO billing (...) VALUES (....) ; ";
$query .= "UPDATE billing SET .... ; ";
if(!mysqli_multi_query($link,$query)){
...
}
Otherwise you can still do just do two single queries and execute them one after the other

Insert values with if condition with mysqli

I am trying to make register member page. If a new member insert an email which has been already exist, then there will be a notification saying that the email is exist. But if the email has not been exist, the values they insert in the form will be send to database.
I don't know what is wrong with my code bellow. It just blank and doesn't send anything to databse. I need a help.
<?php
//conection:
$link = mysqli_connect(".com","klaudia","intheclaud","elektro") or die("Error " . mysqli_error($link));
//consultation:
$member_id=$_GET['member_id'];
$member_name=ucwords(htmlspecialchars($_POST['member_name']));
$member_email=$_POST['member_email'];
$member_password=htmlspecialchars($_POST['member_password']);
$member_phone=$_POST['member_phone'];
$member_address_satu=ucwords(htmlspecialchars($_POST['member_address_satu']));
$member_address_dua=ucwords(htmlspecialchars($_POST['member_address_dua']));
$member_reference=$_POST['member_reference'];
$query = "SELECT * FROM member_registry WHERE member_email='$member_email '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)";
?>
I have tried to check the connection and the database. Everything works fine here. When I insert someone name which has been in the table of the database, it will echo that the email already exist. and vice versa.
$query = "SELECT * FROM member_registry WHERE member_name='Klaudia '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
echo "This email you are using has NOT been registered before";
}
[UPDATE]
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)");
}
?>
You shouldn't handle this by two separate queries (at least without a transaction).
Instead create a unique index that doesn't allow the same email address twice in the table and check for the specific ER_DUP_ENTRY error code to detect doublets.
sscce:
<?php
define('MYSQL_ER_DUP_ENTRY', 1062);
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error('connection failed', E_USER_ERROR);
}
$result = $mysqli->query('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
email varchar(128),
primary key(id),
unique key(email)
)'
);
if ( !$result) {
trigger_error('create table failed', E_USER_ERROR);
}
$stmt = $mysqli->prepare('INSERT INTO soFoo (email) VALUES (?)');
if (!$stmt) {
trigger_error('prepare failed', E_USER_ERROR);
}
$result = $stmt->bind_param("s", $email);
if ( !$result) {
trigger_error('bind_param failed', E_USER_ERROR);
}
foreach( array('email1', 'email2', 'email1') as $n=>$email ) {
echo $n, ' ', $email;
$result = $stmt->execute();
if ( $result ) {
echo " ok\r\n";
}
else {
if ( MYSQL_ER_DUP_ENTRY==$stmt->errno ) { // <-- here's the test for the duplicate entry
echo " duplicate\r\n";
}
else {
var_dump($stmt->errno, $stmt->error);
}
}
}
prints
0 email1 ok
1 email2 ok
2 email1 duplicate
You have an error in your syntax. You don't close your function.
Also you shouldn't use single quotes around your coumn names.
mysqli_query($link, "INSERT INTO member_registry (
`member_id`,
`member_name`,
`member_email`,
`member_password`,
`member_phone`,
`member_address_satu`,
`member_address_dua`,
`member_reference`)
VALUES (0,1,2,3,4,5,6,7,8)");

Categories