I got empty result with MySQL - mysql

I have tried to show the whole table data in MySQL. Rows are (User_id, first_name, last_name, and dept). There is no result when I refresh the page.
<?php
$servername = "fdb19.awardspace.net";
$username = "2598428_db";
$password = "password";
$dbname = "2598428_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * From users";
$result = $conn->query($sql);
while($res = mysqli_fetch_array( $result )) {
echo $res['AverageSatisfactionScore'];
}
?>

Your echo is false.
You need to display a valid column name like :
echo $res['id'] or echo $res['dept'].

just try to print the total count of your result set by
echo mysqli_num_rows( $result );
it will print total number of records in the result
Also try to print whole row by
print_r($res);
insted of using
echo $res['AverageSatisfactionScore'];

Related

fetchAll from database using PDO

So I've been working on this website a long time but the problem is most of it is MYSQL, which of course isnt very secure, so now I'm trying to update all the PHP to PDO, so far I've only managed to get the connect.php working (in the first code below). My main issue is wthin the 2nd code below, on my reviews page I'm having a hard time fetching ALL the reviews from database including (cid,uid,username,date,message & rating) and then ORDER BY DESC, I have used multiple guides but they all seem to show a different way of doing it...
<?php
$host = 'localhost';
$dbuser = 'B99';
$dbpwd = 'testpass';
$dbname = 'admin';
//set DSN//
$dsn = 'mysql:host=' . $host .';dbname=' . $dbname;
//Create PDO instance//
//Attempt MySQL server connection.//
$pdo = new PDO($dsn, $dbuser, $dbpwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and the FetchAll code here:
<?php
include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");
$sql = $pdo->query("SELECT * FROM `reviews` ORDER BY `cid` DESC");
$stmt = $pdo->prepare($sql);
$stmt->execute(['cid']);
$reviews = $stmt->fetchAll();
foreach ($reviews as $fetch) {
?>
<div class="eachreview" style="background-color:royalblue;">
<?php echo $fetch['rating']; ?>
<?php echo $fetch['uid']; ?>
<?php echo $fetch['message']; ?>
<?php echo date("d/m/Y" ,strtotime($fetch['date'])); ?>
</div>
<?php
}
?>
UPDATED CODE Kinda working but displaying 1/1/1970 and no other data
<?php
include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");
$stmt = $dbh->prepare("SELECT * FROM `reviews` WHERE cid = :cid");
$stmt->execute(array(':cid' => "cid"));
$fetch = $stmt->fetchAll();
{
?>
THIS CODE BELOW WORKS! :)
<?php
include("/var/www/vhosts/my-web.co.uk/httpdocs/PHP/connect.php");
$stmt = "SELECT * FROM `reviews`";
$result = $dbh->query($stmt);
foreach ($result as $fetch) {
?>
<?php echo $fetch['message']; ?>

How to make reference to one of my MySQL databases inside my PHP file?

I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>

Check if email already exists in database and add/change data

I've got a form which has 14 numeric inputs and 2 text inputs - name and email. Someone is adding data and it's saved to the database - I've done it. But when someone is adding data for the second time using the same email address, database should override the data in specific row with that email.
I read about UPDATE in sql but I don't know how to make a query which will check if that email exists and after that add or update data.
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "test";
$quantity = $_POST['quantity'];
$quantity2 = $_POST['quantity2'];
$quantity3 = $_POST['quantity3'];
$quantity4 = $_POST['quantity4'];
$quantity5 = $_POST['quantity5'];
$quantity6 = $_POST['quantity6'];
$quantity7 = $_POST['quantity7'];
$quantity8 = $_POST['quantity8'];
$quantity9 = $_POST['quantity9'];
$quantity10 = $_POST['quantity10'];
$quantity11 = $_POST['quantity11'];
$quantity12 = $_POST['quantity12'];
$quantity13 = $_POST['quantity13'];
$quantity14 = $_POST['quantity14'];
$name = $_POST['name'];
$email = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Saved.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use insert . . . on duplicate key update. You can do this if you have a unique key on what you want to be unique:
create unique index idx_results_name_email (name, email);
Then, the database will enforce uniqueness. The statement you want is:
INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')
ON DUPLICATE KEY UPDATE 1paracwierc = VALUES(1paracwierc),
1paracwierc2 = VALUES(1paracwierc2),
. . .
final2 = VALUES(final2);

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

using mysqli instead of mysql accessing the DB

please find below a script in php that that fetch data from my database company, the database is in phpMyadmin
I understand that there are secure ways to fetch data. My question is
Can I improve the code below using mysqli to fetch instead of mysql_query.
<?php
get results from database. Can I improve the code below using mysqli to fetch instead of mysql_query in the following line?.
$result = mysql_query("SELECT * FROM customer")
or die(mysql_error());
tables begins here with the customer id and customer name
echo "<table >";
echo "<tr>
<th>ID</th> the customer id
<th>Name</th> the customer name
</tr>";
// loop through results of database query, displaying them in the table
the table below display the columns in html using mysql fetch array. all data is displayed.
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
my purpose is embed the php in html in another way using msqli
echo "<tr>";
echo '<td>' . $row['CustomerID'].'</td>';
echo '<td>' . $row['Name']. '</td>';
echo "</tr>";
}
echo "</table>";
?>
my purpose is embed the php in html in another way using msqli
Just replace all the mysql with mysqli
$result = mysqli_query("SELECT * FROM customer");
while($row = mysqli_fetch_array( $result )) {
If you wanna keep it simple
Or do it like this...
/*Your connection info goes here...*/
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM customer";
if ($result = $mysqli->query($query)) {
echo "<table ><tr><th>ID</th><th>Name</th></tr>";
/* fetch results by row */
while ($row = $result->fetch_row()) {
echo "<tr><td>' . $row['CustomerID'].'</td><td>' . $row['Name']. '</td></tr>';
}
/* free the result set */
$result->close();
}
/* close the connection */
$mysqli->close();