<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include 'conn.php';
// Attempt select query execution
$db_select = mysqli_select_db($conn,'college');
if (!$db_select) {
die("Database selection failed:: " . mysql_error($conn));
}else{
} //You don't need a ; like you do in SQL
$result = mysqli_query($conn,"SELECT * FROM college") or die("error".mysqli_error($conn));
echo "<table>"; // start a table tag in the HTML
$result = array();
while($row = mysqli_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['city'] . "</td><td>" . $row['clients'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysqli_close($conn);
?>
I am getting error in query statemenet that table college does exist. I have created table college in phpmyadmin and populated it with fake values, but still I am getting query error. The error is in line 14.
Related
So my 1st target is to convert expecting data from mySQL as JSON before use XML.
Things i trying to solve- Connect two tables from database for specific user and display it on screen.
Everything is in one PHP file:
<?php
include 'db.php';
session_start();
ob_start();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users
INNER JOIN user_quiz ON users.user_uid = user_quiz.user_uid
WHERE users.user_uid = '".$_SESSION['u_uid'] ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
// for check if record exist
echo "<br> id: ". $row["id"]. " - Name: ". $row["user_first"]. " " . $row["user_last"] . " id:" . $row["user_uid"] . " Selected qustion " . $row["q_topic"] . " ". $row["q_id"] . "<br>";
}
} else {
echo "0 results";
}
$myJSON = json_encode($outp);
echo $myJSON;
?>
So now where is a issue.. When i do SQL like that:
SQL:
$sql = "SELECT * FROM users";
PHP is convert data as JSON data... but when i trying to do that for specific user i have empty []... That's why i use echo to see if i have output or i have error but... i have displays value... Had no idea what's going on... need advice.
I have an HTML table displaying data from a MySQL database. I want to add a "delete row" button, so that with a click I can delete a row from the database table (data linked to the Member's ID).
I can see what the SQL should be doing, but I don't know how to implement it with PHP.
I also have a search page where you can search for a member by inputting their first name and I want to add the same delete function to that search page too.
But for now I want to get it working on an HTML table that shows all the data first!
Here is my code (minus the connecting and disconnecting from database and all that):
// Retrieve Member Details
$sql = "SELECT MemberID, FirstName, Surname, DOB, Address, County,
PostCode, MobileNo, Email FROM Members";
$result = mysql_query($sql, $connection);
//create table
echo "<table>";
// Loop through the data and then display chosen data
echo "<h2>Member Details</h2>";
echo "<tr><th>Member ID</th><th>First Name</th><th>Surname</th>
<th>DOB</th><th>Address</th><th>County</th><th>Post Code</th>
<th>Mobile Number</th><th>Email</th><tr>";
while($a_row = mysql_fetch_assoc($result))
echo "<tr><td>" . $a_row['MemberID']
. "</td><td>" . $a_row['FirstName']
. "</td><td>" . $a_row['Surname']
. "</td><td>" . $a_row['DOB']
. "</td><td>" . $a_row['Address']
. "</td><td>" . $a_row['County']
. "</td><td>" . $a_row['PostCode']
. "</td><td>" . $a_row['MobileNo']
. "</td><td>" . $a_row['Email']
. "</td><tr>";
//close table
echo "</table>";
Code for Search page:
<?php
// Connecting to Database Server
$connection = mysql_connect("localhost", "1520621",
// If connection cannot be made to Database Server
if (!$connection)
die("Cannot connect to Database");
// Select the database
mysql_select_db("db1520621", $connection)
// If Database cannot be found
or die("Cannot find Database");
// SQL
// Select all data from Members table where FirstName matches that which is inserted into searchName using POST
$sql ="SELECT * FROM Members";
$sql.=" WHERE FirstName=\"".$_POST["searchName"]."\"";
// Execute the query
$queryResult=mysql_query($sql);
//Check for errors and display following messages if there is
if (mysql_error())
{
echo "Problem with Query<br>";
echo "The following error message was returned from MySQL:<br>";
echo mysql_error();
exit;
}
//Create table
echo "<table>";
echo "<h2>Member Details</h2>";
echo "<tr><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><tr>";
// If no results found show message. If results found, loop if there is more than 1 result
if (mysql_num_rows($queryResult)==0)
{
echo "No members with that name";
}
else
{
while ($dbRecord=mysql_fetch_array($queryResult))
{
echo "<tr><td>".$dbRecord["FirstName"]."</td><td>".$dbRecord["Surname"]."</td><td>".$dbRecord["DOB"]."</td><td>".$dbRecord["Address"]."</td><td>".$dbRecord["County"]."</td><td>".$dbRecord["PostCode"]."</td><td>".$dbRecord["MobileNo"]."</td><td>".$dbRecord["Email"]."</td></tr>";
}
}
// Close connection to Database
mysql_close($connection);
?>
You should be using PHP Data Objects (http://php.net/manual/en/ref.pdo-mysql.php) or MySQLi (http://php.net/manual/en/book.mysqli.php).
The Ending <tr> table on the echo line is not closed (</tr>) which might be messing with the HTML output.
SQL query for deleting:
$query = sprintf("DELETE FROM Members WHERE MemberID = '%s'",
mysql_real_escape_string($member_id));
Here is the full code to delete row from database. First you have to add delete link and pass member id to be deleted.
// Check if delete button is clicked and delete respective row
if(isset($_GET['DeleteID']) AND !empty($_GET['DeleteID']))
mysql_query("DELETE FROM Members where MemberID = '".$_GET['DeleteID']."'", $connection);
// Retrieve Member Details
$sql = "SELECT MemberID, FirstName, Surname, DOB, Address, County, PostCode, MobileNo, Email FROM Members";
$result = mysql_query($sql, $connection);
//create table
echo "<table>";
// Loop through the data and then display chosen data
echo "<h2>Member Details</h2>";
echo "<tr><th>Member ID</th><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><th>Delete</th><tr>";
while($a_row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $a_row['MemberID'] . "</td><td>" . $a_row['FirstName'] . "</td><td>" . $a_row['Surname'] . "</td><td>" . $a_row['DOB'] . "</td><td>" . $a_row['Address'] . "</td><td>" . $a_row['County'] . "</td><td>" . $a_row['PostCode'] . "</td><td>" . $a_row['MobileNo'] . "</td><td>" . $a_row['Email'] . "</td>";
echo "<td>Delete</td></tr>";
}
//close table
echo "</table>";
Search page code
<?php
// Connecting to Database Server
$connection = mysql_connect("localhost", "1520621", "w9p1n5");
// If connection cannot be made to Database Server
if (!$connection)
die("Cannot connect to Database");
// Select the database
mysql_select_db("db1520621", $connection)
// If Database cannot be found
or die("Cannot find Database");
// SQL
if(isset($_GET['DeleteID']) AND !empty($_GET['DeleteID']))
mysql_query("DELETE FROM Members where MemberID = '".$_GET['DeleteID']."'", $connection);
// Select all data from Members table where FirstName matches that which is inserted into searchName using POST
$sql ="SELECT * FROM Members";
$sql.=" WHERE FirstName=\"".$_REQUEST["searchName"]."\"";
// Execute the query
$queryResult=mysql_query($sql);
//Check for errors and display following messages if there is
if (mysql_error())
{
echo "Problem with Query<br>";
echo "The following error message was returned from MySQL:<br>";
echo mysql_error();
exit;
}
//Create table
echo "<table>";
echo "<h2>Member Details</h2>";
echo "<tr><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><tr>";
// If no results found show message. If results found, loop if there is more than 1 result
if (mysql_num_rows($queryResult)==0)
{
echo "No members with that name";
}
else
{
while ($dbRecord=mysql_fetch_array($queryResult))
{
echo "<tr><td>".$dbRecord["FirstName"]."</td><td>".$dbRecord["Surname"]."</td><td>".$dbRecord["DOB"]."</td><td>".$dbRecord["Address"]."</td><td>".$dbRecord["County"]."</td><td>".$dbRecord["PostCode"]."</td><td>".$dbRecord["MobileNo"]."</td><td>".$dbRecord["Email"]."</td>";
echo "<td>Delete</td></tr>";
}
}
// Close connection to Database
mysql_close($connection);
?>
I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
I am fetching data from mysql to a page, i am not sure if the way im doing it is appropiate. I am having trouble with fetching values into sections of the page.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "xxx") or die (mysql_error ());
// Select database
mysql_select_db("xxx") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM news";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
}
// Close the database connection
mysql_close();
?>
</div> <!-- content #end -->
the database;
the above yields;
I want to do the following;
BY: Fadi
echo 'BY' $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
but it isn't working :( any tips
You are missing a concat operator after 'BY'. Should be
echo 'BY' . $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
OR tidier:
echo "BY {$row['editor_name']} {$row['news_desc']}<br/>";
If you want to return associative array you can try using this line:
...
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
...
You forgot one dot after 'BY'
echo 'BY' . $row['editor_name'] . ' ' . $row['news_desc'] . '<br />';