Fail to insert data into mysql using php - php

Checking with phpcodechecker not showing the error but can't insert data into mysql.
PHP version: 5.6
Server type: MariaDB
here the code
header('Access-Control-Allow-Origin: *');
include "config.php";
$dblink = mysqli_connect($host,$dbu,$dbp,$db);
if (!$dblink) {
error_log( "Error: Unable to connect to MySQL." . PHP_EOL);
error_log("Debugging errno: " . mysqli_connect_errno() . PHP_EOL);
error_log("Debugging error: " . mysqli_connect_error() . PHP_EOL);
exit;
}
if (isset($_GET['name']) &&isset($_GET['score'])){
$name = strip_tags(mysqli_real_escape_string($dblink, $_GET['name']));//get data from column USER
$score = strip_tags(mysqli_real_escape_string($dblink, $_GET['score']));//get data from column HIGHscore
$sql=("SELECT * FROM scores WHERE name='$name';");//choose userdata table from database where column USER
$result = $dblink->query($sql);//execute database
if ($result->num_rows > 0){ //if result > 0, if any data on tables
$row = $result->fetch_assoc();
if ((int)$row['score'] < (int)$score){ //score on database less than score input will execute database
$sql=("INSERT scores SET name='$name', score='$score' ;"); //Update score
if ($dblink->query($sql) === TRUE) {
echo "Success";//this is if success
}
else
{
echo "Error updating record: " . $dblink->error;//this is if failed or error
}
}
}
}
// echo not effect
mysqli_close($dblink);
whether the use of .htaccess affects data insert ?
SOLVED
Delete this code if ($result->num_rows > 0) {

The format of your INSERT query is wrong (you have used the UPDATE form). You should use:
INSERT INTO scores (name, score) VALUES('$name', '$score')
See the manual...
In PHP:
$sql = "INSERT INTO scores (name, score) VALUES('$name', '$score')";

Related

column doesnt match when its empty

How should i solve this? there is not a row 1 and i cant insert or update data. Unique keys are indeed ip and uid in my table.
My code is as follows:
//Retrive listeners per reload
echo 'Data Höganäs <br>';
$sc="http://USER:PWD#SUB.SERVER.se:10000/admin.cgi?sid=1&mode=viewxml&page=3";
$xml2 = simplexml_load_file($sc);
foreach ($xml2->LISTENERS->LISTENER as $listener2) {
// Create connection
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " insert INTO hoganaskey
(ip, uid, tid, starttid, date)
VALUES
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
on duplicate key
update tid='$listener2->CONNECTTIME' ";
//$sql = "INSERT INTO hoganaskey (ip, uid, tid, ua, starttid, date) VALUES('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT' '$starttid', '$date') ON DUPLICATE KEY UPDATE tid='$listener2->CONNECTTIME' ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} //End foreach SHOUcast listener
Im returning this error in insert "Column count doesn't match value count at row 1".
In your insert query, you listed only 5 field names:
(ip, uid, tid, starttid, date)
but you are passing 6 values not 5:
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')

How to insert data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one insert in table "TabelaX" which is in another database. I already made some code but it is not working correctly. And this error appears:
"Error: INSERT INTO TabelaX (ID, Nome, Dados) VALUES (2000, XPTO2,
12345); Unknown column 'XPTO2' in 'field list'Error: INSERT INTO
TabelaX (ID, Nome, Dados) VALUES (2033, XPTO3, 1234567890); Unknown
column 'XPTO3' in 'field list'"
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Nome"];
$row3 = $row["Dados"];
mysqli_select_db($conn,"Servidor1");
$sql = "INSERT INTO TabelaX (ID, Nome, Dados)
VALUES ($row1, $row2, $row3);";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
From what I have read, your current approach might be the only way to do this using regular queries with MySQL. But, if you were doing this directly on MySQL, you could just use a simple INSERT INTO ... SELECT:
INSERT INTO db1.TabelaX (ID, Nome, Dados)
SELECT ID, Nome, Dados
FROM db2.TabelaY;
One possibility would be to create a stored procedure on MySQL which does the above insert, and then call it from your PHP code:
$result = mysqli_query($conn,
"CALL YourProcName") or die("Query fail: " . mysqli_error());

I would like to avoid importing duplicates records but ON DUPLICATE KEY UPDATE is not working

I have a table in dbf file.
I am writing PHP script to import data from dbf file to the mysql using PHP and ODBC connection.
So I have file called ffc. It has four columns file, format,commons,dbf. The dbf file does not have primary key.
I created a table in mysql with 4 fields. I also added an 'id' field as primary key.
I am writing PHP to import records from dbf file to the mysql. But if records exist update (if record has been updated in dbf file) and move to next records and add new record if record does not exist.
I am using ON DUPLICATE KEY UPDATE file but it is not working.
WHen I run the script first time; all records get imported. But when I run the script again they get imported again.
Here is code.
<?php require_once('../database.php'); ?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
error_reporting(E_ERROR | E_PARSE);
//ODBC connection
$connectionstring = odbc_connect("foxpro", "", "");
//Select statement to pull data
$q1 = "SELECT * FROM ffc.dbf";
$rw = odbc_exec($connectionstring, $q1);
//Loop through to insert data into mysql
while ($rs = odbc_fetch_array($rw)) {
//print_r($rs);
$file = $rs['file'];
$format = $rs['format'];
$commons = $rs['commons'];
$dbf = $rs['dbf'];
//Insert/Update query
$test_query = "INSERT INTO test (file, format, commons, dbf) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE file = ?, format = ?, commons = ?, dbf = ?;";
if(!($stmt_test_query = $mysqli->prepare($test_query))) {
echo "Prepare (1) failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if(!($stmt_test_query->bind_param('iiiiiiii', $file, $format, $commons, $dbf,$file, $format, $commons, $dbf))) {
echo "Bind params (1) failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if(!($stmt_test_query->execute())) {
echo "Execute (1) failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
?>

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 ****/

Why are extra empty rows generated in mysql table when using php insert variables

I have tried to insert variable to mysql table from submitted html form. However, I observed that 3 rows is generated while I have just inserted 1 row of data variable. The problem disappeared when the data is not variable. This problem annoyed me very much. Hope problems can be solved. Thank you very much.
Below is the coding of creating the table:
<!DOCTYPE html>
<html>
<head>
<title>Server Database</title>
</head>
<body>
<span style='font-size:24;font-weight:bold;'>Server Database</span>
<br /><br />
<?php
$host="localhost";
$port=3306;
$socket="";
$user="root";
$password="";
$dbname="";
$conn = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
echo "it work"."<br>";
$SCusName=$_POST['CusName'];
$SCusChiName=$_POST['CusChiName'];
$SDate=$_POST['Date'];
$sql = "CREATE DATABASE db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully"."<br>";
} else {
echo "Error creating database: " . $conn->error;
}
mysqli_select_db($conn,"db")
or die ('cannot select');
$sql = "CREATE TABLE Requests (
RequestNumber INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
CustomerName VARCHAR(50),
ChineseName VARCHAR(50),
DateOfRequest VARCHAR(30)
)";
if ($conn->query($sql) === TRUE) {
echo "Table Requests created successfully"."<br>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql = "INSERT INTO Requests (CustomerName, ChineseName, DateOfRequest)
VALUES ('".$SCusName."', '".$SCusChiName."', '".$SDate."');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "SELECT BbKeyID, CustomerName, ChineseName FROM Requests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "BbKeyID: " . $row["BbKeyID"]. " CustomerName: " . $row["CustomerName"]. " ChineseName: " . $row["ChineseName"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
The result in mysql table become contains three row as follow with a message 3 row(s) returned:
The first row contains correct data while the other two rows are empty in value only with the auto-incremented RequestNumber. Is the RequestNumber make the problems?
1 Result 1 Result 2 Result 3
2
3
The empty values are not NULL.
If the insert data is changed to:
$sql = "INSERT INTO Requests (CustomerName, ChineseName, DateOfRequest)
VALUES ('AAA', 'BBB', 'CCC')";
The result become correct and only one row given out as follow.
1 Result 1 Result 2 Result 3
Please help me to solve the problem. Thank you very much..
You run your INSERT query EVERY TIME the page is loaded, even if no form was submitted. So if the page is fetched via GET, you'll have undefined $_POST data, and insert empty strings.
You should have at least
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do db insert stuff here ...
}
to "hide" the code from non-post requests.
And you are vulnerable to sql injection attacks. Enjoy getting your server pwn3d.

Categories