Echoing out mysqli data with php? - 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();

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;
}

"No database selected" when implementing Zebra_pagination with SQL/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()

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!

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

simple php - Mysql search not working properly

I have this code:
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
?>
The goal is to search my mysql database to find the result of $_POST['clientsearch'] in one of the fields and return the lines that have that word in it (it is always 1 word)
If I use this:
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."'"")
it seems to work. but it only searches in the FNAME column, not all of them. Also I only get the first result back. not all.
I'm starting php/mysql so I'm a little lost and don't know all functions yet. Could someone explain how I could fix my code up?
Thanks a lot for your help :)
For starters, you'll need to loop through each row in your result set if you're expecting more than 1 row. I illustrate how to do this with your original code.
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// Print out the contents of the entry for each row in result
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
}
?>
Take a look in the PHP documentation on mysql_real_escape_string for starters on the injection stuff.
Also, as others stated you may be looking for the LIKE instead of = SQL syntax. Also, look into the % wild card for LIKE.
Not an answer to the question, but hopefully helpful. Try writing code like this:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");
Exactly how you indent is up to you. This approach helps a great deal with readability, and hence also debugging :)

Categories