"No database selected" when implementing Zebra_pagination with SQL/PHP - php

Relatively new to PHP and first Stack question, so apologies in advance for any mistakes on my part.
I'm trying to implement Zebra Pagination with my SQL database (using latest MAMP) and getting an error of 'No database selected'. I think the issue lies in how I'm hooking up my connection with Zebra, but not having a ton of luck debugging. The code:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// how many records should be displayed on a page?
$records_per_page = 10;
// include the pagination class
require 'Zebra_Pagination.php';
// instantiate the pagination object
$pagination = new Zebra_Pagination();
$MySQL = "SELECT SQL_CALC_FOUND_ROWS Id
FROM table
LIMIT
' . (($pagination->get_page() - 1) * $records_per_page) . ', ' . $records_per_page . '
";
$result = $conn->query($MySQL);
// if query could not be executed
if (!($result = #mysql_query($MySQL))) {
// stop execution and display error message
die(mysql_error());
}
// fetch the total number of records in the table
$rows = mysql_fetch_assoc(mysql_query('SELECT FOUND_ROWS() AS rows'));
// pass the total number of records to the pagination class
$pagination->records($rows['rows']);
// records per page
$pagination->records_per_page($records_per_page);
?>
<table class="Id" border="1">
<tr><th>Id</th></tr>
<?php $index = 0?>
<?php while ($row = mysql_fetch_assoc($result)):?>
<tr<?php echo $index++ % 2 ? ' class="even"' : ''?>>
<td><?php echo $row['Id']?></td>
</tr>
<?php endwhile?>
</table>
<?php
// render the pagination links
$pagination->render();
$conn->close();
?>
I'm guessing there's just some dumb beginner's mistake in here. Any/all help would be much appreciated!

I would be sure to test your credentials using the "mysql" command locally or a graphical tool such as Sequel Pro (open source, donationware).
To cite Zebra's source code:
Please note that this is a generic pagination script, meaning that it does not display any records and it does not have any dependencies on database connections or SQL queries, making it very flexible! It is up to the developer to fetch the actual data and display it based on the information returned by this pagination script. The advantage is that it can be used to paginate over records coming from any source like arrays or databases.
So the issue likely does not lie with Zebra. While it's possible it is a permissions issue, either way it's very likely a mis-configuration between your PHP and your MySQL, as referenced here: PHP says "No Database selected" even after using mysqli_select_db()

Related

How to create a simple dropdown list with php linking to mysql database

Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}

how to do multiple if statemnts in php based on a criteria

I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer

How to fetch data as it is from MySql Database using PHP

I am trying to fetch Data from MySQL Database using PHP script from Server. I am able to get Data from Database, but I am not getting the exact string present in Database. In the result obtained the spaces between words get trimmed and result does not match with String present in Database.
For Example:
The value inserted to Database is as shown Below:
SELENIUM INTERVIEW QUESTIONS:
What is Selenium?
Selenium is a set of tools that supports rapid development of test automation scripts for web based applications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.
What are the main components of Selenium testing tools?
Selenium IDE, Selenium RC and Selenium Grid
The result obtained from the Database query shows the data as:
SELENIUM INTERVIEW QUESTIONS:What is Selenium?Selenium is a set of tools that supports rapid development of test automation scripts for web basedapplications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.What are the main components of Selenium testing tools?Selenium IDE, Selenium RC and Selenium Grid
Can any one please let me know what changes should I make in my script to obtain data as it is shown in database from my query. I am using mysql_real_escape_String while inserting and I am using stripslashes while retrieving data from database.
Below is my PHP script:
Insert Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedName = urldecode($_POST['enteredName']);
$obtainedUserName = urldecode($_POST['enteredUserName']);
$obtainedsubjectText = urldecode($_POST['subjectText']);
$obtaineddetailsText = urldecode($_POST['detailsText']);
$status = urldecode($_POST['status']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$obtainedsubjectText = $conn->real_escape_string($obtainedsubjectText);
$obtaineddetailsText = $conn->real_escape_string($obtaineddetailsText);
$sql = "INSERT INTO AndroidTable (Name, UserName, Subject, Details, Status)
VALUES ('$obtainedName', '$obtainedUserName', '$obtainedsubjectText', '$obtaineddetailsText', '$status')";
mysqli_commit($conn);
if ($conn->query($sql) === TRUE) {
echo "Inserted Post sent to Moderator for Approval. Once approved from Moderator, Post will be displayed";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
fetch Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedUserName = 1;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT Name, Subject FROM AndroidTable WHERE Status ='" .$obtainedUserName. "'";
$result=mysqli_query($conn,$sql);
while ($row = mysqli_fetch_row($result)) {
foreach($row as $rows){
for($i=0;$i<count($rows);$i++){
echo stripslashes($rows) . " ";
$n=$i;
}
}
echo "<br/>";
}
$conn->close();
?>
Please let me know what mistake am I doing in my script. All suggestions are welcome. If more information required please let me know. Thanks in advance.
You can use nl2br, which will convert new line characters to <br>, so wherever you are echoing, you just need to call nl2br function, see example below:
echo nl2br(stripslashes($rows)) . " ";
EDIT:
To get spaces instead of <br>, you can simply replace new line character \n with space, or anything you would like to replace with, see example below:
echo str_replace("\n", " ", stripslashes($rows))
EDIT 2:
echo stripslashes(str_replace(array('\r\n', '\n'), "<br>", $rows));

Echoing out mysqli data with php?

I am trying to get my head round mysqli so i can update my site and make it more secure. I have an article in a database and I am trying to echo it out like i would with mysql. I have seen loads and loads of posts here about basic mysqli but cannot find a way to get this to work. So i apologize if i have asked a question that has already been asked but what i have so far is mainly a result of what I have found here.
I am getting the following error:
Fatal error: Cannot use object of type mysqli_result as array in C:\xampp\htdocs\workshop\msqli-test.php on line 20
Here is the code i have so far:
<?php
$DBServer = 'localhost';
$DBUser = 'root';
$DBPass = 'pass';
$DBName = 'test_db';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM articles WHERE title = "Simple Ideas For Your Website Logo."';
$row=$conn->query($sql);
echo "<div class='articlepreviewlayoutreadmore'><a href='".$row['link']."'>Read Full Article</a></div>";
echo "<img src='".$row['images']."' />";
echo "<h3><a href='".$row['link']."'>";
echo $row['title']."</a></h3>";
echo "<h6>Author: ".$row['author']."</h6>";
echo "<h6>Published:".$row['timestamp']."</h6>";
echo "<p>".$row['content']."</p>";
echo "<div class='articlepreviewlayoutreadmore'><a href='".$row['link']."'>Read Full Article</a></div>";
?>
Thanks in advance for any help with this, i am getting old and keeping up to date with programming languages gets harder year after year.
You've missed a step. After you execute your query you get a result object returned. You then need to use that to get your results:
$sql='SELECT * FROM articles WHERE title = "Simple Ideas For Your Website Logo."';
$result = $conn->query($sql);
$row = $result->fetch_assoc();

Nesting MySQLI Queries

I am trying to pull a number from one table inside a database, and then use that number to process a query on another table in the same database.
The code doesn't spit out any errors - it just doesn't return a string! I am trying to understand mysqli and the whole array structure, but I'm having difficulty figuring out why this isn't working. I believe I am trying to successfully turned the original array into a string for use in the second query, which I also translate into a string for the echo. It's just that for some reason it's not printing anything! If I take out the nested loop then it prints the active_event number just fine. I'm at a loss!
<?php
$DBServer = 'localhost';
$DBUser = 'user';
$DBPass = 'pass';
$DBName = 'database';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$get_active_event = mysqli_query($conn, "SELECT active_event FROM asp_config");
while($active_event = #mysql_fetch_assoc($get_active_event)){
$get_event_name = mysqli_query($conn, "SELECT * FROM asp_events WHERE id = {$active_event['active_event']}"); echo $get_event_name->fetch_object()->event_name;}
$conn->close();
?>
Thanks!
-Philip
I suggest to change the logic of your piece of code modifying you db schema in a more efficient way.
I'd fetch the results in a single query joining the two tables asp_config and asp_events or, even better, if possible get rid of asp_config and add a column is_activeor something like this to asp_events table.
Then you just have to cycle with while-loop without the second query because all you need to know is in the first results set.
Be careful to use the error suppression (#) you need to know if there is an error and handle it. Suppress without knowing it's a bad pratice
Unfortunately joining the two tables isn't an option, and I have other queries that need to use the same type of functionality so merging all of the tables into one just isn't doable. That all said, I did figure it out. I think the biggest issue was that I wasn't exiting out of the SQL mode before trying to insert the PHP variable, so I ended up querying a null row which returned a blank dataset. The final code I used is:
<?php
$DBServer = 'localhost';
$DBUser = 'user';
$DBPass = 'pass';
$DBName = 'actionsports';
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($con->connect_error) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$get_active_event = mysqli_query($con,"SELECT * FROM asp_config");
while($active_event = mysqli_fetch_array($get_active_event))
{
$get_event_name = mysqli_query($con, "SELECT * FROM asp_events WHERE id=('" .$active_event['active_event'] ."')");
if ($get_active_event === false) {
exit("Error: " . mysqli_error($con));
}
while($event_name = mysqli_fetch_array($get_event_name))
{ echo $event_name['event_name'] ;}}
$con->close();
?>
In this case I do have a query loop inside another loop, and it does return the correct data. It might not be the prettiest code, but it works and is what is required for my situation.
Thanks for the help!

Categories