SQL query and PHP - php

I have following code.
<?php
$server = „host databaze“;
$dbuser = „jmeno uzivatele“;
$dbpass = „heslo uzivatele“;
$dbname = „jmeno databaze“;
mysql_connect($server, $dbuser, $dbpass);
mysql_select_db($dbname);
$result = mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“);
echo $result;
?>
there is syntax error on line with mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“);
I cant solve problem but I think it is not working because mysql_query(„SELECT jméno FROM nazevtabulky WHERE id=3“); not returns string.. Pls help

the problem appears to be in either:
Czech-style quotations - you should use "", not „“ (may be similar on settings above that)
Czech-style naming - the column is probably called jmeno, not jméno.

Make sure you are using double quotes ("")
$result = mysql_query("SELECT jmeno FROM nazevtabulky WHERE id=3");

Related

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!

Select query that returns question mark while selecting malayalam string from a table

My php code is below:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db="newsportaldb";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($db,$dbhandle)
or die("Could not select DB");
$sql= mysql_query('select username from tbl_login');
while($rss= mysql_fetch_array($sql))
{
$ress["homepagecontents"][] = array("titles"=>$rss['username']);
}
echo json_encode($ress);
mysql_close($dbhandle);
?>
//in this case we getting "?????????????????" as a result of echo json_encode($ress);
The Question marks come from wrong charset.
Make sure that the connection has right charset (utf8).
If on phpmyadmin you dont see the data correctly so change the db,table and column to utf8_general_ci.
Hot recommend for you: upgrade your code and use php PDO Object.
Good luck !

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'];
}
?>

How to show image using php?

I am just starting to use html, php, and mysql. I've successfully logged into my database using php, and formed a query. I now want to go a step further and show a picture instead of just strings or numbers.
The variable 'result' will be returning a string that has a url to an image i want to display on this webpage. How would I do this?
<html>
<head>
<title>My First Question</title>
</head>
<body>
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
echo 'Successfully connected to database!';
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
?>
</body>
</html>
Inside PHP, This will turn your SQL response into a usable variable.
$result = mysql_fetch_assoc(mysql_query($query));
Outside of your PHP tags, Echo the URL from the table into the SRC of an IMG element.
<img src="<?= $result['url_column_name'] ?>"/>
This will create a new IMG element with the source being the URL that you have fetched from your SQL query.
Short tags are also a way of echoing PHP variables in HTML.
<?= $var1, $var2 ?>
is the equivalent of using
<?php echo $var; echo $var2; ?>
This is a simple case of echoing the relevant HTML. You'll also have to fetch the results after you execute the query -
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo '<img src="'.$data['image'].'" />;
For added security, a good practice would be to escape any possible unwanted HTML content in your images path - htmlspecialchars($data['image']).
It should also be noted here that you are using a very old deprecated method to access your database. You might want to think about updating your code to use more modern PDO methods.
So what? simply use it as a source to your image
<?php $imgname = mysqli_fetch_array($connection, $result); ?>
<img src="<?php echo $imgname['image_column_name']; ?>" />
And btw use mysqli_() or PDO instead of using mysql_() as community is not maintaining it anymore
Once you update your mysql to mysqli you can echo the image's url in an html img tag as so:
echo '<img src="'.$result['image'].'"/>';
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
header("Location: $result");
?>
should work

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