i would like to ask for an idea of how to fetch information from my database without getting everything in it. For example: i have an article that is consisted of 10 paragraphs in my database but i would only want to fetch 200 characters from it (so that i could have sustained information for my articles preview). Thanks in advance
currently i am using this code to fetch my data but it gives me everything from the database
$result = mysql_query("SELECT * FROM tblArticles Where id='".$_POST['num']."'");
$count=mysql_num_rows($result);
if($count>0)
{
$row = mysql_fetch_array( $result );
$id=$row[0];
$title=$row[1];
$contents=$row[2];
}
Try (make sure you change the field names in the SQL query to the actual field names):
$result = mysql_query("
SELECT id AS article_id,
article_title,
SUBSTRING(article_content, 1, 200) AS article_content
FROM tblArticles
WHERE id='" . mysql_real_escape_string($_POST['num']) . "'");
$count=mysql_num_rows($result);
if($count>0)
{
$row = mysql_fetch_assoc( $result );
$id=$row['article_id'];
$title=$row['article_title'];
$contents=$row['article_content'];
}
I've added the MySQL function SUBSTRING() to the SQL query. This will retrieve a partial string from a whole string. For example, substring(field, 1, 100), will retrieve all the text between character 1 and character 100 from the field.
You should also avoid using MySQL_* functions. There not recommended for use in new code. Instead, look into PDO or MySQLi
Related
I have a field (Description) in a MySQL database (poi). I wish to use php and the strip_tags to remove the HTML from all the records in the database. I then want to update the result to the same Description field in the database.
I have no problem with obtain the string and stripping the HTML, but I just can't seem to work out how to update the database with the result.
// check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$sql_article = "SELECT Description FROM poi";
$result = $mysqli->query($sql_article);
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
}
Ideally each row will have a unique id column that you can use to specify which row to update using a prepared statement:
$sql_article = "SELECT id, Description FROM poi";
$result = $mysqli->query($sql_article);
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE id = ?");
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
$stmt->bind_param("si",$Description_no_html,$row['id']);
$stmt->execute();
}
If you don't have a unique id column, then use the following statement instead
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE Description = ?");
and
$stmt->bind_param("ss",$Description_no_html,$row['Description']);
Alternative: stripping tags directly in mysql
You can create a custom mysql function that strips tags (https://stackoverflow.com/a/13346684/3574819) and use the following query
UPDATE poi SET Description = strip_tags(Description)
Disclaimer: I'm not sure how well the above referenced mysql strip_tags works, so your mileage may vary depending on your content.
I'm developing an app for android that uses a DB on a server.
I wrote some script php to create new rows in some tables and get all elements from a table (using JSON to exchange data between android and mysql).
Now I have a problem:
i need to select an id from a table and then use this to insert a row in anothere table that has this foreign key.
Well, when I try to select my id, i don't know why, but look like it doesn't work.
Here a simple example how I select this id:
//connect to DB...
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
When i use this to select an id, and put it in another query (always on the same connectio) nothing is stored.
if I force the value manually, and so in the same second query I put a number of a preesisting id, the insert works, so the problem is in this piece of code.
Hope someone could help me.
Thank you!
The code that you have put on the question, contains syntax errors.
- Remove * from the start of query
- put the query inside " "
- remove single quote ('table') from table name
Here is the modified code:
//connect to DB...
$result = mysql_query ("SELECT id FROM table WHERE name = $name" );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Also you should escape the parameter $name in query. And you should use mysqli or PDO instead of mysql extension.
try this:
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
while($row > 0){
$id = $row['id'];
}
OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.