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'];
}
?>
Related
I'm relatively new to any type of programming or coding. I'm not quite understanding why no matter what adjustments I make to my php file I can't seem to pull any data from a table.
Here is a link to the table: https://i.gyazo.com/4ad5e860895014c49dbe0539c38cdec2.png
Above is the test table I have been trying to use. From what I can understand I'm connecting to the database okay, but all of my problems come after the connection. Also, I'm using php 7.0 so a lot of the information I'm finding online has not been helpful.
If there is something glaringly wrong with my table or in my code, please let me know.
Here is my code:
'''
//Set Variables
$serverName = "localhost";
$userName = "root";
$password = "";
$databaseName = "test";
//Create Connection
$connection = mysqli_connect($serverName,$userName,$password,$databaseName);
//Check Connection
if(!$connection){
die("Connection failed: ".mysqli_connect_error());
}
echo "Connected successfully <br>";
//Fetch Data
$query = "SELECT * from table1";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ($row[1], $row[2]);
mysqli_free_result($result);
mysqli_close($connection);
I figured out the issue a few hours ago. The code I had posted would have worked perfectly fine if I was connecting to the port for MySQL rather than MariaDB. Didn't realize that the port that MariaDB was connected to was the default.
MariaDB by default was port 3306, but MySQL was 3308. After specifying 'localhost:3308' I was able to start properly pulling rows from my tables.
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!
I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>
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 :)
I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.