SQL Query error in PHP - php

This is a code for a cafeteria, and this is the login.
<?php
$userna = 'root';
$paso = '';
$mach = 'localhost';
$db ='cafeteria';
session_start();
// GET PAGES RECORD FROM LOG TABLE: *********| Only the first time though:
if (isset($_SESSION['log']) != 'logging')
{
// Here, just creating a string:
$pages_record = "";
$insert_query = '';
// Get saved pages from the database:
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Error in log-page script: AB-1 - query: $insert_query." . mysqli_error($connection));
mysqli_select_db($connection,'cafeteria');
// Query string to pull all pages from table record:
$get_pages_query = "select * from log-page";
// Query the database, and save result:
$query_pages_result = mysqli_query($connection, $get_pages_query);
// Check number of results returned:
$num_of_results = '';
$num_of_results = mysql_num_rows($query_pages_result);
if ($num_of_results > 0)
{
// Loop through the result array: Each time, one row, and then the next one ...
for ($row = 0; $row < $num_of_results; $row++ )
{
// Getting one row:
$get_row = mysqli_fetch_array($query_pages_result);
// Extracting just the page name from the row:
$one_page = substr($get_row["page"],strripos($get_row["page"],"/") + 1);
// Adding this page name to the string created previously:
if ($row == 0)
{
$pages_record .= $one_page;
}
else
{
$pages_record .= ",".$one_page;
}
}
// Once all pages have been read and saved to the string
// now we save it to the session:
$_SESSION['logpages'] = $pages_record;
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
else
{
// There are no pages in the table:
$_SESSION['logpages'] = "";
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
}
// Check if page is already in session list.
$pages_array = array();
if (strlen(isset($_SESSION['logpages'])) > 0 )
{
// string variable that holds all pages separated by commas:
$pages_string = $_SESSION['logpages'];
// creating an Array to hold all pages already logged in server:
if (strstr($pages_string, ","))
{
$pages_array = explode(",", $pages_string);
}
else // just means there's only one page in the record
{
// so, we push it inside the array.
array_push($pages_array, $pages_string);
}
// current page: [ We are extracting only the page, not the entire url, Exmp: login.php ]
$current_page = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Check if current_page is in the array already:
if (!in_array($current_page, $pages_array))
{
// IF is NOT in the array, then add it:
array_push($pages_array, $current_page);
// Add it to the Session variable too:
$pages_string = implode(",", $pages_array);
// Re-save it to SESSION:
$_SESSION['logpages'] = $pages_string;
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(`date`, `time`, `page`, `user`) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection, $insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
else
{
// IF it IS in the list, just SKIP.
}
}
else
{
// means, that there are absolutely no pages saved in the database, basically this is the first log:
$_SESSION['logpages'] = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(date, time, page, user) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection,$insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
?>
But now i am getting this error:
Error in log-page script: AB-2 - query: INSERT INTO log-page (date,
time, page, user) VALUES ('2012-10-16', '16:58:44',
'/caf/pages/index.php', '').You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near '-page (date, time, page, user)
VALUES ('2012-10-16', '16:58:44' at line 1
Im using Xampp 1.8.1 PHP: 5.4.7. It does not let me login neither as administrator nor as a cashier

Enclose the table name in backticks like this (rest of the query omitted):
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) ... ";
Otherwise MySQL will try to interpret the - as a minus sign, which fails in this case.
EDIT
IN the last insert shown, also the column names should be enclosed in backticks:
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) VALUES ...";

Try escaping field name
(`date`, `time`, `page`, `user`)

It's been a while since I looked at mySql docs, but it looks to be complaining about the table name "log-page". Try quoting that table name.

Related

insert data from a table and insert into another table in different database

I have 2 database that link together. I need to retrieve data from that table and insert those column into a table in different database based on their Unique id number.
<?php
$handle = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_query("USE shop",$handle);
$query = "SELECT ModelCode,Class FROM shopfloor_pro WHERE CommNo = '0985560712'";
$result = mysql_query($query);
while ($data = mysql_fetch_object($result)){
$variable1 = $data->ModelCode;
$variable2 = $data->Class;
mysql_query("USE vt",$handle);
$sql = "INSERT INTO track SET
t_model_code = '$variable1',
t_class = '$variable2' WHERE t_comm_no = '0985560712'";
if (!mysql_query($sql)) {
echo '<p>Error adding data into database: ' . mysql_error() . '</p>';
}
mysql_query("USE paintshop",$handle);
}
?>
this is the data that i want to retrieve
this is where i want to put the data
When i run the code it shows
"Error adding data into database: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE t_comm_no = '0985560712'' at line 3"
You can most likely do this in a single query - but as pointed out the mysql api has been deprecated a long time ago and totally removed from PHP 7+.
To do the query in a single operation you might try like this:
insert into `vt`.`track` (`t_model_code`,`t_class` )
select `ModelCode`,`Class` from `shop`.`shopfloor_pro` where `CommNo`='0985560712'

loop for to insert row in a mysql database with php

I have a for loop with php but is not working properly. Inside the for loop I have an "if" and an "else", but the loop stops iterate in the first "else" and should continue. Here is the code:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
} //end of else
} //end of for
The thing is if the database contain 5 rows and I want to insert, for example, 10 rows, the code works updating the first 5 with the new value, then it jumps to the "else" and starts to iterate in the sixth value and it works, but the next values doesn't.
Any idea what i'm doing wrong? Thanks!
Hector
Ok I found the problem. In the else loop, when the iteration tries to select the database, for some reason it takes part of the name of the last iteration, so it couldn't find the database. The solution (maybe is not so clean) is connect and close the database connection in every iteration. The code stays like this:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
// reconnect to db
$con = mysqli_connect($host, $user, $pass) or die ("unable to connect");
$db = "database";
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
//close the connection to db;
$con->close();
} //end of else
} //end of for
Thanks you all for inspiring the answer!
Hector

PHP insert and Update on Multiple Query and table

in there i want to make update and create on one condition,so when I create a new record, automatically update my Data if have i success make new.
here my PHP :
<?php
require "dbconnection.php";
$a = array();
$a['transidmerchant'] = $_POST['TRANSIDMERCHANT'];
$a['totalamount'] =$_POST['AMOUNT'];
$a['words'] = $_POST['WORDS'];
$a['payment_channel'] = $_POST['PAYMENTCHANNEL'];
$a['session_id'] = $_POST['SESSIONID'];
$a['payment_date_time'] = $_POST['REQUESTDATETIME'];
$a['trxstatus'] = 'Requested';
$query = "INSERT INTO doku (transidmerchant,totalamount,words,payment_channel,session_id,payment_date_time,trxstatus)
VALUES ('$_POST[TRANSIDMERCHANT]','$_POST[AMOUNT]','$_POST[WORDS]','$_POST[PAYMENTCHANNEL]','$_POST[SESSIONID]','$_POST[REQUESTDATETIME]','Requested')";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
if(mysqli_query($con,$query)) {
mysqli_connect($con,$sql);
echo 1;
}else{
echo("Error description: " . mysqli_error($con));
}
my query : $query and $sql
i want my $sql its update when $query is success create
if (mysqli_query($con, $query) === true) {
mysqli_query($con, $sql);
echo 1;
} else {
echo('Error description: ' . mysqli_error($con));
}
Create a stored procedure for insert then update. You may want to do something like this to get you away from issuing regular queries checking sub-queries and move you to creating a stored procedure.
Create your procedure to something similar below and run it in your sql dialog. Once you're done, run it:
DELIMITER //
CREATE PROCEDURE Payment
(
a_transidmerchant int,
a_atotalamount float,
a_words varchar(200),
a_payment_channel varchar(200),
a_session_id int,
a_payment_date_time datetime,
etc...
)
BEGIN
insert into doku(field_name1, field_name2, field_name3, field_name4) values(a_field1, a_field2, a_field3, a_field4);
END //
DELIMITER;
Now, in your php file, do the following:
if(isset($_POST[transidmerchantid])) /**** start a post check ****/
//before you touch the db
{
$con = mysqli_connect("localhost","user","pass","database");
//start defining variables
$transidmerchantid = $_POST[name];
$totalamount = $_POST[course];
$words = $_POST[words];
//calling stored procedure - call values for parameters in stored procedure
$sql = "CALL Payment('$transidmerchantid','$totalamount','$words')"; // <----
//in the order of operation, meaning once you have inserted the data,
//you can update the table. you're automatically updating the table row
//based on a successful insert, which is after calling the insert row
//stored procedure.
$result = mysqli_query($con,$sql);
if($result) //insert successful.
echo "Record Added Successfully!";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
mysqli_query($con,$query);
}else{
echo("Error description: " . mysqli_error($con));
}else{
echo "Record Not added!"; //insert unsuccessful.
}
} /**** end post check ****/

Update query works but not insert query

I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.

PHP MySql Update else Insert Error "Warning: mysql_result()"

I'm trying to go threw my table nonbulkmdu and look into r10database to find if there is a duplicate, if there is it will update 4 fields if its not it will insert a new row. I keep getting the error
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in on line 19-23.
What am I doing wrong?
<?php
$username="";
$password="";
$database="";
$link = mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM nonbulkmdu";
if ($result=mysql_query($query, $link)) {
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$address=strtoupper(mysql_result($result,$i,"address"));
$drops=mysql_result($result,$i,"drops");
$city=mysql_result($result,$i,"city");
$citycode=mysql_result($result,$i,"citycode");
$feature_type=mysql_result($result,$i,"Feature_Type");
$result = mysql_query("update r10_database
set drops=$drops, citycode=$citycode, city=$city, Feature_Type=$feature_type
where address=$address;");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ($address,
$drops,
$city,
$citycode,
$Feature_Type);");
}
$i++;
}
} else {
echo mysql_error();
}
mysql_close();
?>
You're missing quotes around the values in the UPDATE and INSERT call:
$result = mysql_query("update r10_database
set drops='$drops', citycode='$citycode', city='$city', Feature_Type='$feature_type'
where address='$address';");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ('$address',
'$drops',
'$city',
'$citycode',
'$Feature_Type');")
BTW, if address has a unique key in the table, you can do both queries at once, using INSERT ... ON DUPLICATE KEY UPDATE.

Categories