PHP Mysqli SELECT, INSERT and UPDATE from different databases - php

I am trying to select values from one DB. And insert and update the result into another. This is cronjob that needs to run everyday to replicate some data from one DB into another. I know I am missing steps / correct syntax, but I hope someone can help me out.
<?php
$con_1=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$con_2=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con_1,"SELECT id, name FROM table GROUP BY 1,2");
$mysqli->query($con_2, "INSERT INTO `table2`(`id`, `name`) VALUES ('".$result[1]."', ".$result[2].")
ON DUPLICATE KEY UPDATE name = ".$result[2]."");
}
mysqli_close($con_1);
mysqli_close($con_2);
?>

mysqli_query returns a query object, using $result[1] doesn't make sense, you need to fetch the rows in a loop:
while($row = $result->fetch_assoc()) {
// insert result in second database
}
For other access methods check the documentation.

Related

How can I get mysql to print rows from a database table

I am trying to learn php from W3schools which includes a mysql section.So far I have completed every other part of the tutorial on w3school except the part that prints content from a database table. For some very weird reason , nothing displays when I run my code. Please how can I get this working and could my problem come from the fact that I am using MariaDB with Xampp instead of Mysql although they said it was practically the same syntax.
Here is the code
<?php
$servername = "localhost";
$username = "uhexos";
$password = "strongpassword";
$database = "fruitdb";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE fruitDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);
// sql to create table
$complexquery = "CREATE TABLE MyFruits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FruitType VARCHAR(30) NOT NULL,
FruitTaste VARCHAR(30) NOT NULL,
FruitQuantity INT NOT NULL,
DatePurchased TIMESTAMP
)";
if ($conn->query($complexquery) === TRUE) {
echo "Table Fruits created successfully<br> ";
} else {
echo "Error creating table: " . $conn->error;
}
$entry = "INSERT INTO myfruits (fruittype,fruittaste,fruitquantity) VALUES ('orange','sweet','50'),('lemon','sour','10'),('banana','sweet','15')";
if ($conn->query($entry) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $conn->error;
}
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['fruitname']} <br> ".
"EMP SALARY : {$row['fruittaste']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
this is the output I get from all my echos.
Error creating database: Can't create database 'fruitdb'; database existsError creating table: Table 'myfruits' already existsNew records created successfully
or
Database created successfullyTable Fruits created successfully
New records created successfully
Based on the error message, you managed to create the database and tables once and now each time you run the code it fails because you can't reuse the names.
You definitely don't want to have code trying to erase & start fresh on your database every time. In fact, most often I find that you don't even create the database inside your regular code but use phpMyAdmin or some other admin page to do that. But creating tables inside code is normal enough. Two options:
1 - Create the table only if it does not already exist. This is extremely safe. However, if you want to start a table over again with a new structure, or start with it always empty, that won't work. To do that, just change CREATE TABLE to CREATE TABLE IF NOT EXISTS
2 - Delete the table before creating it. Before each CREATE TABLE command, add a command like DELETE TABLE IF EXISTS MyFruits
Remember database name is Case-insensitive, so it doesn't matter whether you create a DB name "fruitdb" or "fruitDb" both are same.That is the reason you are getting error. Also you don't have to create a new database when you execute any file. If you have already created the database than you only have make the connection with it.
Let's debug your code line by line.
Line 8 -
// Create connection
$conn = new mysqli($servername, $username, $password);
Here you are creating the connection with your database because you have already created that database. If you check your phpmyadmin, you'll find a database named "fruitdb"
Line 10 -
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Here your checking whether the you are able to connect with your database. If not it will throw the error and your script will stop. Right now your code successfully runs till this point.
Line 15 -
// Create database
$sql = "CREATE DATABASE fruitDB";
Here you are again creating a database with same name and your code stops working as you already have it.
The error was from this line
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
I accidentally put fruitname instead of fruittype and that is what caused it to fail. So for anyone else with thi problem my advice is to check your variable names if you are 100% sure of your syntax. Thanks for all the help.

how to insert data in mysql database using mysqli with data checking no same "id" in same "date"

guy's i need your help. im trying to make an insert form with php with this condition.
"id cant be same in same date"
my database name is : "ssl",
table name is : "try"
with table col: "id", "date", "name", "city"
im have try a lot to make this but still get some eror. but when i delete the php script for checking it can running well..
please help me. im really apreciated when you give me an example of that.
sorry for my english and sorry im still newbie and need study more for something like this
this my script for insert
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "silo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql="Insert into termocouple
Select * from temp1";
if(mysqli_query($link, $sql)){
echo "Data inserted successfully.";
} else{
echo "Data inserted Failed " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
can i just use something like this?
i get from Copy rows from one table to another, ignoring duplicates
<?php
$sql="INSERT INTO termocouple
SELECT no,tanggal,silo,...
FROM temp1
WHERE NOT EXISTS(SELECT *
FROM destTable
WHERE (temp1.no=termocuple.no and
temp1.tanggal=termocouple.s_tanggal...etc.)
)";
?>

Inserting a value to a table which is present in more than one database

Could someone let me know how to insert a set of values into a table across different databases .
Example : I have a table by name TABLE inside Database1 , Database2 ....
Is there a way where I can insert values into the TABLE present in both the databses.
I tried doing
Insert into Database1,Database2.Table(type)values('1');
But it did not work .
Thanks for your help
Unfortunately Table names, column names, etc. cannot be dynamic in mysql, you can try to create dynamic queries
$databases = list of dbs;
foreach ($databases as $db){
$query = "Insert into".$db.".tableName()....."
}
since you are using php you can use mysqli_select_db(connection,dbname); to select different database using it.
for Eg.
//create a connection
$conn = mysqli_connect("host","user","password","db_name");
//list of databases
$databases = "Your Array of database";
foreach ($databases as $database){
// Change database to $database
mysqli_select_db($conn,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect :" . mysqli_connect_error();
}
// code for $database eg. - your insert query...
}

MySql Select Command returning null

I have a simple php code which enters value into MySql database and then retrieves it and displays it. However when retrieving it always return null and Empty Set is echoed everytime. Can someone please help.
I am using WAMP Server.
Database name is trial and name of table is People. It has 2 attributes: name and email id
Following is my code:
$con=mysqli_connect("localhost","root","");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_query($con,"INSERT INTO People VALUES ('xyz', 'abc#zzz.com')");
echo "Insertion Success";
$result = mysqli_query($con,"SELECT * FROM People");
if($result == null)
echo "Empty Set";
else
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . " " . $row['emailid'];
echo "<br>";
}
mysqli_close($con);
?>
You should select a database after using mysqli_connect but before any queries are done:
$con=mysqli_connect("localhost","root","");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_select_db($con, "databasename");
//query processing here..
You should check if record is inserted change your code to
if( mysqli_query($con,"INSERT INTO People VALUES ('xyz', 'abc#zzz.com')") === FALSE){
echo mysqli_error();
}
first always check if you query executed write by executing it inside if():
if(!mysqli_query("your query"))
{
mysqli_error();
}
second i think your query is not executing because you cant name you table with a capital letter so it should be "people" not "People"

Endless while loop

I am trying to post some table rows into a database. I have created a while loop and it keeps posting my first HTML table row to the database. The desired behaviour is that every HTML table row is posted to the DB.
<?PHP
$con=mysqli_connect("localhost","root","","freoplanner");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count=1;
$shiftDate='dp'.$count;
$shiftTime='shiftTime'.$count;
$shiftAantal='shiftAantal'.$count;
while(isset($_POST[$shiftDate]) && !empty($_POST[$shiftDate])){
$sql="INSERT INTO shifts (datum, tijd, aantal)
VALUES
('$_POST[$shiftDate]','$_POST[$shiftTime]','$_POST[$shiftAantal]')";
$count++;
mysqli_query($con,$sql);
}
header("location:shiftstoevoegen.php");
?>
You need to reinitialise the following inside the loop:
$shiftDate='dp'.$count;
$shiftTime='shiftTime'.$count;
$shiftAantal='shiftAantal'.$count;
currently, they will always be using $count = 1

Categories