Select by id mysql php - php

I would like to select rows by id and show it. My Table is named text
And this is whats in the table
BookID Type init
Title
Author
PublisherName
CopyrightYeare
here is how i would like to call them
text id 10
by this action i get row nummber 10 and i get all the information in
BookID, Title, Author, PublisherName, CopyrightYeare
If I query this
text id 14
by this action i get row nummber 14 and i get all the information again.
<?php
function text($id){
$query = "SELECT * FROM text WHERE BookID =" .$id ;
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
}
?>
<?php
echo text (14) ;
?>

You have a few problems.
You are using the obsolete mysql_* functions. Consider upgrading to mysqli
You are vulnerable to SQL injection attacks. Again, look at mysqli and read up on how to use prepared statements correctly.
Your function is named text, you are calling displaytext
Your function is not returning a result. At the end of the function, add return $row; to get the results back

You are calling a function called displytext() but the function is called text().
The function text() does not return a value so the echo will have nothing to print.

Sorry for the late reply, just had another gander and here is a working code.
Problems wre
You did not return anything from your functions
You did not escape the $id which would leave it prone to SQL injection
The previously stated function name,
I hope this sorts it for you. See the code bellow
<?php
function text($id){
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM text WHERE BookID = $id";
$row = mysql_fetch_assoc(mysql_query($query));
return $row;
}
print_r(text('1'));
?>

Related

Displaying Datafield from mySQL in WP Shortcode

I am trying to display field data in the WP front end using shortcodes from a new table.
See Table
After coming across many sources and research, I do not seem to find a simple way to display data in text (not table), contained within a specific field selected in the SQL query by means of SELECT FROM WHERE.
So far I called wpdb, selected the field, created a loop and echoed. But no results are displayed.
I also tried using print_r and implode but both failed too.
<?php
function Initial_Brief(){ global $wpdb;
$results = $wpdb->prepare( "SELECT 'Initial_Brief'* FROM `Portal_100` WHERE Project_Title = 'Project 1'");
foreach ($results as $result)
echo $result['results'];
}
add_shortcode('Initial_Brief','Initial_Brief')
?>
Many thanks in advance,
To share the logic of this, which I find quite powerful, is to use shortcodes for displaying all text on the website, enabling text edit from the front-end by creating an HTML form which updates the specific field. I will create an edit icon displayed on hover to an editor's role, clicked to trigger a popup with an html form which calls a function to update the specific field in the database.
You are missing to call the get_results method like this:
<?php
global $wpdb;
$id = 23;
$sql = $wpdb->prepare( "SELECT * FROM tablename WHERE id= %d",$id);
$results = $wpdb->get_results( $sql , ARRAY_A );
?>
The use of the prepare method is a good practice for preparing a SQL query for safe execution (eg. preempt SQL injection), but it is no yet the execution, it returns a sanitized query string, if there is a query to prepare.
It is also good companion for the query method.
After some iterations I finally got it to work!
I understand mySQL does not accept input with a spacing?
How can I insert a WHERE condition for multiple words or a paragraph?
It worked for me using the following script but I had to change the WHERE value into an integer.
<?php
add_shortcode('Initial_Brief', function(){
global $wpdb;
$sql = $wpdb->prepare("Select Value from `P100` WHERE `P100`.`id` = 1 ");
$results = $wpdb->get_results( $sql , ARRAY_A );
foreach ($results as $result) {
$display = implode(", ", $result);
echo $display;
});?>

Display PHP code on web page

I am creating a library for PHP scripts and I want to be able to show php code on a html webpage.
I have looked at using highlight_file(); but this will show the whole page
For example, If I have a page called code.php which has an sql query on ( select code from table where sequence = $_GET["id"] ) - example then I use
Highlight_file('code.php?id=123');
This will work but will also show the select query which I do not want to show. I would just want to show the code from the database (code column)
How can I display just the code from the database with the correct colours and formatting etc
UPDATE:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
I have tried the above code, which is just displaying the code in plain text
use highlight_string function, like this:
<?php
highlight_string($code);
?>
where $code is the code you have obtained from your SQL query.
You can create a function around this (something along the following lines):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
UPDATE:
Your code is a bit incorrect, you can use:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
Note that you do not need to include $conn in your function, it can be ommitted. Also, note that you should use mysqli->* family of functions, since mysql_* family has been deprecated.
Perhaps this would work for you.
This post is originally for HTML, but the answer linked above shows an example using PHP.

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

php function save result at array

hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>

Categories