Inserting xml values in table no success - php

Trying to get my xml feed into a table, missing something as not working.
Warning: mysqli_query(): Couldn't fetch mysqli in
/Users/John/Sites/XMLproject/Update Emperor.php on line 77
//Database variables
$servername = "localhost";
$username = "Something";
$password = "Very secret";
$dbname = "TestDB";
$temptable = "wlbvx_jb_xml_emperor";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: ","<strong>",$dbname,"</strong>","<br>" ;
?><br><?php
$url = "http://bookings.emperordivers.com/webScheduleSpecificXML_all.asp";
$feed = file_get_contents($url);
$xml = simplexml_load_string($feed);
//Row by row into variable, then into table
foreach ($xml->Schedule as $row) {
$ID = "Null";
$start = date("d-m-Y", strtotime($row->Start));
$duration = $row->Duration;
$boat = $row->Boat;
$itinerary = $row->Itinerary;
$spaces = $row->Spaces;
$rateseur = round(str_replace(',', '', $row->Rates->Rate[0]));
$rategbp = round(str_replace(',', '', $row->Rates->Rate[1]));
$rateusd = round(str_replace(',', '', $row->Rates->Rate[2]));
$sql = "INSERT INTO $temptable (id,xml_date, xml_duration, xml_boat, xml_itinerary, xml_spaces, xml_rate_eur, xml_rate_gbp, xml_rate_usd)VALUES ('{$ID}',{$start}', '{$duration}', '{$boat}', '{$itinerary}','{$spaces}', '{$rateseur}', '{$rategbp}', '{$rateusd}')";
echo "SQL Query to execute:",$sql,"<br>";
mysqli_query($conn, $sql);
}
What could cause the issue?

Related

Always MySQL output nothing. Tell me why?

<?php
$uname = $_POST["username"]$uname =
stripslashes(trim($uname));
$pward = $_POST["password"];
$pward = stripcslashes(trim($pward));
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "index_data";
$conn = new mysqli($servername, $username,
$password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM 00_user_details WHERE
username = '$uname' ";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_row($result);
echo "_".$rows["first_name"]."_";
?>
I am a bigger.
It's my code but it outputs nothing .
Any if you respected sir/ma'm help me kindly...
Please put semicolon after $_POST["username"] and use mysqli_fetch_assoc in place of mysqli_fetch_row.
mysqli_fetch_assoc return a row as an associative array where the column names will be the keys storing corresponding value.
Please find actual code as below:
$uname = $_POST["username"];
$uname = stripslashes(trim($uname));
$pward = $_POST["password"];
$pward = stripcslashes(trim($pward));
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "index_data";
$conn = new mysqli($servername, $username,$password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM 00_user_details WHERE username = '$uname'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_assoc($result);
echo "_".$rows["first_name"]."_";

Notice: Array to string conversion in C:\xampp\htdocs\tes1.php on line 19

I'm sorry if this question is may already similar to others question. I certainly success to make a connection to database. I'll try to show all the databases that I have. But when I tried with my code, i got this error.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = mysqli_query($conn,'SHOW DATABASES;');
$names = array($sql);
foreach ($names as $key => $value) {
$row = mysqli_fetch_array($value);
echo $row.'<br />';
}
?>
$sql = mysqli_query($conn,'SHOW DATABASES;');
$row = array();
while ($row[] = mysql_fetch_array($sql)) {
print_r ($row) ;
}

How to combine two MySQL connections into one MySQL connection?

I have two MySQL connections for the same database in the one .php file.
Second connection is base on the result of First one.
How can I combine two connection into one ? Please help & teach me how to modify it ?
First connection:
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);
// select data
$sql = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$pageTitle = $row['com_eng_name'] . $row['com_chi_name'];
$com_no = $row['com_no'];
$br_no = $row['br_no'];
$com_eng_name = $row['com_eng_name'];
$com_chi_name = $row['com_chi_name'];
$com_type = $row['com_type'];
$date_of_incorp = $row['date_of_incorp'];
$active_status = $row['active_status'];
$date_commenced_dormancy = $row['date_commenced_dormancy'];
$remarks = $row['remarks'];
$date_of_dissolution = $row['date_of_dissolution'];
$register_charges = $row['register_charges'];
$name_history = $row['name_history'];
$phone = $row['phone'];
$email = $row['email'];
$address = $row['address'];
$website = $row['website'];
$background = $row['background'];
$update_time = $row['update_time'];
}
} else {
echo "No Results";
}
$conn->close();
?>
Second connection:
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// select data for similar search
$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));
$sql = "SELECT * FROM ComData
WHERE com_eng_name REGEXP '$words'
ORDER BY com_no
DESC
LIMIT 20";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>CR No.</th><th>Company Name</th><th>Active Status</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["com_no"]."</td><td><a href='search.php?crno=".$row["com_no"]."' >".$row["com_eng_name"]." ".$row["com_chi_name"]."</a></td><td>".$row["active_status"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
If those 2 pieces of code both exist in the same physical file then as the variable holding your connection in both cases is $conn you can just throw away the second attempt at making a connection to the database.
So just remove of comment out this code from the piece of code you called Second Connection i.e. this bit
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then remove this line
$conn->close();
from the piece of code you called First Connetion so you do not close the connection before the second piece of code runs.
However if in fact those 2 pieces of code are in seperate .php files. they have to stays the way they are.
It's not clear either if your two connection are in the same page or not, and if your two queries are execute sequentially or alternately.
Anyway, if the queries are on the same page or if you want put it in same page, sure you can use one only connection.
Start your script in this way:
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
then, if you have to performs both queries, continue in this way:
// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);
// select data
$sql = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
(...)
} else {
echo "No Results";
}
// select data for similar search
$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));
(...)
$conn->close();
Otherwise, if the queries are executed only on condition, after connection check continue in this way:
if( /* Your Condition Here */ )
{
// Logic data
$previous_page = ($_GET['crno'] - 1);
(...)
}
else
{
// select data for similar search
$string = "$com_eng_name";
(...)
}
If you want use connection in any different file, you can create a file dbconnect.php with this content:
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, in each file with db query, include it in this way:
header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// Logic data
$previous_page = ($_GET['crno'] - 1);
(...)
header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// select data for similar search
$string = "$com_eng_name";
(...)
etc...
Please note that, depending on 'dbconnect.php' file location, you can have to change include( 'dbconnect.php' ) with include( '/Full/Or/Relative/Path/dbconnect.php' ).

extracting an array from a database in php

im currently trying to extract a table from my database (articles) and the table article and put it in an array but im not sure weather or not it wokred because i dont know how to print an array. i was following this link.
http://phpscriptarray.com/php-arrays-tutorials-tour/how-to-extract-mysql-database-data-into-php-array-variable.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
// connect to DB
$db_selected = mysqli_select_db('article', $conn);
if (!$db_selected){
die("can't use article : " .mysqli_error());
}
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = mysqli_query($query);
$number = mysql_numrows($result);
$article_array = array();
$x = 0
while($x < $number)
{
$row = mysqli_fetch_array($result);
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
$x++;
}
echo count($article_array);
//echo "hello";
<?
even the echo hello wont work and im not sure if i was supposed to put a name and quantity in:
$artic = $row['name'];
$amount = $row['quantity'];
You are mixing object oriented with procedural style. Your query and loop should look like this:
$query = "SELECT * FROM `articles`";
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
}
http://php.net/manual/en/mysqli.query.php
Also your PHP closing tag is faulty - should be ?> or omitted.

mysqli_query giving me unsolvable message

I am trying to make a basic song info page, and my only problem is the SQL. I keep getting this message:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in /var/www/tts/recommend-action.php on line 33
Here is my code:
<?php
session_start();
ini_set("display_errors",true);
ob_start();
$host = "localhost";
$user = "root";
$pass = "[MYPASSWORD]";
$db = "[MYDATABASE]";
$tb = "recommendation";
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
$song = $_POST['song'];
$album = $_POST['album'];
$artist = $_POST['artist'];
$linkitunes = $_POST['linkitunes'];
$artwork = $_POST['albumPic'];
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$link = stripslashes($linkitunes);
$artwork = stripslashes($artwork);
print "<br /><br /><b>User ID: </b>" . $_SESSION['user_id'] . "<br /><b>Song: </b>$song<br /><b>Album: </b>$album<br /><b>Artist: </b>$artist<br /><br />";
$sql = "INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes) VALUES (" . $_SESSION['user_id'] . ", $artist, $song, $album, $artwork, $linkitunes);";
$postrec = mysqli_query($link, $sql);
if ($postrec == true) {
print "sucess";
}
else {
print "<br /><br />failed";
}
ob_flush();
?>
I cannot find a solution. Help is very greatly appreciated.
You connect fine and $link is good:
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
But then later redefine as a string:
$link = stripslashes($linkitunes);
And then you try and use the string:
$postrec = mysqli_query($link, $sql);

Categories