How can i get data from mysql table - php

I have a couple of easy problems.
First I am trying to get names from database where surname='lion'. I wrote php a file but it didn't work:
$con = mysql_connect("localhost","yata_ali","password");
if (!$con){
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'");
if(mysql_query){
return "$degisken";
}
mysql_close($con);
?>
I wrote this code and tried to use $degisken in my xcode project. But it didn't work.
shortly i am trying to use the names whichs surname =lion in my ios project and i know i should use url.but i couldn find the code part that return name what shall i write at the end of php code ? return or something else to use in xcode.
how can i send response in php? i wonder that. what shall i write "return $name" or something else. i know call url. but i dont know whats the full php code that i shall use

You can't use PHP in an iOS project. You'll need to write some objective-c to call a URL on a server which returns this data in some sort of format (xml? json?) and then have the iOS app parse the response.

I don't think you understand how to use the mysql_* functions in PHP. Take a look at the examples on this page for guidance: http://www.php.net/manual/en/function.mysql-query.php

$degisken= mysql_query("select name from people where surname='lion'");
if ($degisken){
while($row = mysql_fetch_assoc($degisken))
{
echo $row["name"] . "<br/>";
}
}

There are a lot of errors, in your code, but the most serious are that
(a) you are running an invalid test:
if (mysql_query){ //YOU CANNOT DO THIS
(b) You cannot return "$degisken"; because $degisken is a MySQL
resource, not a string.
(c) You should not close your mysql
connection after returning something. You don't necessarily need to
close it at all, but if you're going to, close it after the query
because anything after the return won't be evaluated (assuming the
return is triggered).
(d) If you're looking for cases where the surname='lion' then don't use wildcards in the MySQL query. where surname LIKE '%lion%' will match 'scalion','lioness','slioner', etc.
Your code should look something like this:
$con = mysql_connect("localhost","yatanada_ali","sifre");
if (!$con) {
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'") or die('Error: '. mysql_error());
if (mysql_num_rows($degisken)){
//your query could return lots of results, so you may want to loop through results:
while($row = mysql_fetch_array($query)){
$name = $row['name'];
//do something with the name... I'm going to echo it.
echo $name . "<br />";
}
}

Related

How to get a text string from sql database to use in html code

I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...

$result = mysql_query()

I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli

php syntax error - beginner

I'm a beginner and trying to get a handle on php. I have been getting a syntax error that I can't seem to solve. I'll show you the code below and some of the fixes I've tried. If anyone has another idea that would be wonderful. Thank you:)
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("Database query failed: " . mysql_error());
}
while($subject = mysql_fetch_array($subject_set)) {
echo "<li> {$subject['menu_name']} </li>";
}
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = {$subject["id"]}", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
echo "<ul class='pages'>";
while($page = mysql_fetch_array($page_set)) {
echo "<li> {$page['menu_name']} </li>";
}
echo "</ul>";
I get: Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " at line 1
I know the problem is at {$subject["id"]} because I got content back and no error when I put "WHERE id_subjects = 1". I've tried:
{$subject['id']}
{$subject[\"id\"]}
But have gotten the same error...
try
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = '".$subject["id"]."'", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
BTW. you should really move away from mysql_* functions. They are being deprecated, move to PDO or mysqli_*, which are a lot safer as well (you are now vulnerable to sql injection)
If you read back to your post, you can clearly see what's going wrong here.
"SELECT * FROM pages WHERE id_subjects = {$subject["id"]}"
As you can see "id" is not connected to the rest of the rest. That is because with the " you close the string.
To fix this simply use
"SELECT * FROM pages WHERE id_subjects = " . $subject["id"]
Or if you really want to put the variable within the string you can use a single quoted string for the key:
"SELECT * FROM pages WHERE id_subjects = {$subject['id']}"
Personally I am a fan of the first solution. But that is just my opinion.
Well when the while loop finishes looping through, it will have exhausted all the results. $subject['id'] won't have any information simply because $subject no longer has any more entries.
I'm guessing you want to list all the subjects first, then all the pages underneath each subject.
Using mySQL isn't going to be pretty but here's what you want to do. (As Bono said use PDO or mysqli, but here's a solution in psuedocode that will work with mySQL).
loop through first query
print subject name
select pages using subject id
loop through pages under that subject id
print page names
You don't need any quotes when inside a quoted string, just use
"SELECT * FROM pages WHERE id_subjects = {$subject[id]}"

issue when inserting data to database

My code doesn't insert any records to mysql. What is wrong? I am really confused.
I have designed a form and I want to read data from text box and send to the database.
<?php
if(isset($_post["tfname"]))
{
$id=$_post["tfid"];
$name=$_post["tfname"];
$family=$_post["tffamily"];
$mark=$_post["tfmark"];
$tel=$_post["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("university",$link);
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'$name','$family',$mark,$tel)";
mysql_query($insert,$link);
}
mysql_close($link);
?>
You'd better to put quotation mark for id, mark and tel after values in your query. Also as #Another Code said, you must use $_POST instead of $_post in your code. Try this and tell me the result:
<?php
if(isset($_POST["tfname"])) {
$id=$_POST["tfid"];
$name=$_POST["tfname"];
$family=$_POST["tffamily"];
$mark=$_POST["tfmark"];
$tel=$_POST["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("university",$link);
$insert="insert into student
(sid,sname,sfamily,smark,stel) values
('$id','$name','$family','$mark','$tel')";
mysql_query($insert,$link) or die (mysql_error());
mysql_close($link);
}
} else {
die('tfname did not send');
}
?>
Use mysql_query($insert,$link) or die (mysql_error()); to fetch the error message.
With the code you've provided it could almost be anything - to do some tests... have you echo'd something to confirm you are even getting the tfname in POST? Does it select the database fine? Do the fields $id, $mark, and $tel need single quotes around them as well? We need to know more about where the code is not working to provide more help but that snippet appears as though it should be running, in the interim, please use some echo's to narrow down your problem!
Try to run the generated sql query in the sql query browser. Get the query by "echo $insert" statement.
change the $insert to:
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'".$name."','".$family."','".$mark."','".$tel."')";
further set ini_set('display_errors',1) so that php displays the error messages as required.
Lastly, whenever doing a mysql query, try to use or die(mysql_error()) in the query so that if somethings wrong with mysql or syntax, we are aware.
$q = mysql_query($query) or die(mysql_error());

using a PHP script to return values from SQL table

I am attempting to search a SQL table from a PHP script. the SQL table is a word list and in the PHP I call a Python script to do the permutations of a given word. Everything is working until I actually go to execute the mysql_query. I need some formatting advice on how to pass so many values to a Select statement. From what I've seen it needs to be in the form ('a','b','c',...) and this is how it is formatted but I'm not getting a return on the actual execution.
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$con= mysql_connect("127.0.0.1","app","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordlookup");
//Retrieve the data.
$word = $_POST['data'];
$perm = exec("python comb.py $word");
$query="SELECT * FROM words WHERE IN (" .$perm. ")";
print $query;
$sql=mysql_query($query);
print $sql;
mysql_close($con);
?>
This is all of the PHP file, the output from the python call would be in the 'a','b','c'... format and the random prints are just debugging. The print $sql doesn't actually put out anything at the moment.
Thanks,
Kyle
SELECT * FROM words WHERE IN (...)
Your query is missing a condition. WHERE what IN ...? You need to fill in a column name there.
Further, if a query is not working, ask the database why it didn't work:
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
Though solution is strange (use external script executed via exec to calculate permutations?), I'd answer your exact question.
$perm_arr = explode(' ', $perm);
function quote($str) { return "'$str'"; }
$perm_arr = array_map('quote', $perm_arr);
$sql = "select * from words where word in (" . join(', ', $perm_arr) . ")";

Categories