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());
Related
I need to insert values into multiple table. Please correct my code because it just double the inserted value on table_attendace
if(isset($_POST['text']))
{
$text =$_POST['text'];
// insert query
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW())";
$query =mysqli_query($conn,$sql) or die(mysqli_error($conn));
if($query==1)
{
$ins="INSERT INTO table_attendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn));
if ($quey==1) {
$_SESSION['success'] = 'Action Done';
}else{
$_SESSION['error'] = $conn->error;
}
}
}
In the second query, you reused the first query $sql again, instead of using $ins.
It should be
$quey=mysqli_query($conn,$ins) or die(mysqli_error($conn));
you can write two queries in single variable with semicolon then you can save the same data in both table.
And
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn)); -> in this line you placed the $ins variable wrongly instead of $ins.
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW()); INSERT INTO table_ttendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
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')
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')";
I have a table with input of type time and I want to check first if there is a row with the current date and the id of employee, if it was I update the value of the input if not I insert a new row. This is what I have tried but it always inserts a new row even if the condition exists:
<?php
$E1=$_POST['E1'];
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$sql1="SELECT * FROM retards WHERE Date ='Curdate()' AND
IdEmpl='".$_POST["IdEmp"]."' ;";
$result1=mysqli_query($connect,$sql1);
if(!$result1){
die('ERREUR SQL ! <br>'.$sql.'<br>'.mysqli_error());}
if($dt=mysqli_fetch_array($result1,MYSQLI_ASSOC)){
$sql="update retards set E1='$E1' where IdEmpl='".$_POST["IdEmp"]."' AND
Date=CURDATE();";
}
else{
$sql="insert into retards(IdEmpl,Date,E1) values
('".$_POST["IdEmp"]."',CURDATE(),'$E1'); ";
}
$result = mysqli_query($connect, $sql);
if (!$result)
{
echo("Error description: " . mysqli_error($connect));
}
else {
$message ="Effectué avec succès!";
echo "<script type='text/javascript'>alert('$message'); </script>";
}
mysqli_close($connect);
?>
This is known as an upsert which can be done in mysql using the insert ... on duplicate key update syntax.
insert into t (a, b, c) values (?, ?, ?)
on duplicate key update b = ?
Your table should have an appropriate unique index or primary key defined on the column(s) of interest.
This is for a registration form I have created. I cannot include all of my code, but the program checks for blank fields then format using the preg_match function. Then it INSERTS the info registered
My code is:
<?php
/* connection info */
ini_set('include_path','../../includes');
include("dbinfo.inc");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die("Couldn't connect to server. error 3");
?>
<?php
/* Program name: Register.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
// Insert info into database //
{
foreach($good_data as $field => $value)
{
$good_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "INSERT INTO UserInfo (user_id, password, first_name, last_name, city, country, email) VALUES ('$good_data[user_id]', '$good_data[password]', '$good_data[first_name]', '$good_data[last_name]', '$good_data[city]', '$good_data[country]', '$good_data[email]')";
$result = mysqli_query($query, $sql) or die ("Couldn't connect to login");
$row = mysqli_fetch($result);
while ($row = mysql_fetch_assoc($result)) {
$sql2 = "UPDATE TimeStamp SET time = CURRENT_TIMESTAMP where user_id='$good_data[user_id]'";
$result2 = mysqli_query($cxn,$sql2) or die("<p>Couldn't Connect to Login</p>");
include('goodReg.inc');
}
{
echo $message;
extract($good_data);
include('register.inc');
exit();
}
}
}
else
{
include("register.inc");
}
?>
How do I move just the variable to the query and not the whole INSERT string?
There's no need to call mysqli_fetch or mysqli_fetch_assoc. Just do the UPDATE query outside of a loop:
$sql = "INSERT INTO UserInfo (user_id, password, first_name, last_name, city, country, email) VALUES ('$good_data[user_id]', '$good_data[password]', '$good_data[first_name]', '$good_data[last_name]', '$good_data[city]', '$good_data[country]', '$good_data[email]')";
mysqli_query($cxn, $sql) or die ("Couldn't insert into UserInfo: " . mysqli_error($cxn));
$sql2 = "UPDATE TimeStamp SET time = CURRENT_TIMESTAMP where user_id='$good_data[user_id]'";
mysqli_query($cxn, $sql2) or die ("Couldn't update TimeStamp: " . mysqli_error($cxn);
include('goodReg.inc');