how can i brief this queries?
i want to combine them but get specific error alert and different three variable
<?php
$sql = "SELECT content FROM post where title='tv'";
$sql2 = "SELECT content FROM post where title='radio'";
$sql3 = "SELECT content FROM post where title='net'";
$result = $connection->query($sql);
$result2 = $connection->query($sql2);
$result3 = $connection->query($sql3);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tvPrice = $row['content'];
}
}else{
echo "tv error";
}
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$radioPrice = $row['content'];
}
}else{
echo "radio error";
}
if ($result3->num_rows > 0) {
while($row = $result3->fetch_assoc()) {
$netPrice = $row['content'];
}
}else{
echo "net error";
}
?>
Using the IN() you can return only those rows with a title of 'tv', 'radio' and 'net'. Then add the title to the query selection so you know which results a re which.
Then just amend you code to fetch all the results into a rows array and then check for the entries and report errors accordingly
<?php
// make a connection to the database obviously :)
$sql = "SELECT title, content
FROM post
WHERE title IN('tv', 'radio', 'net')";
$result = $connection->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
// better initialise the variables in case you try using them later
$tvPrice = $radioPrice = $netPrice = 0;
foreach ($rows as $row){
if ($row['title'] == 'tv')){
$tvPrice = $row['content'];
}
if ($row['title'] == 'radio') {
$radioPrice = $row['content'];
}
if ($row['title'] == 'net') {
$netPrice = $row['content'];
}
}
if ( $tvPrice == 0 ) echo 'tv error';
if ( $radioPrice == 0 ) echo 'radio error';
if ( $netPrice == 0 ) echo 'net error';
?>
Usually you don't actually need tree (or more) variables; use an array.
<?php
$titles = ['tv', 'radio', 'net'];
// Generate the query
$sql =
"SELECT content, title FROM post WHERE title IN("
. implode(", ", array_map(function( $title ) use( $connection ) {
return '"' . mysqli_real_escape_string($connection, $title) . '"';
}, $titles) )
. ")";
$result = $connection->query($sql);
$prices = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Check for duplicates
if( !empty( $prices[ $row['title'] . 'Price' ] ) )
echo $row['title'] . " has duplicate error";
else
$prices[ $row['title'] . 'Price' ] = $row['content'];
}
}
// Check if we have all desires rows
foreach( $titles as $title )
if( empty( $prices[ $title . 'Price' ] ) )
echo "$title missing error";
// If you really need tree variables instead of array:
extract($prices);
Related
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
}
else {
echo "There are no results matching your search.";
}
}
?>
Check if isset, then trim, then confirm it still has at least one character.
if ( isset( $_POST['submit-search'] ) ) {
$search = trim( (string) $_POST['submit-search'] );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}
}
If you have PHP 7+, here's a more terse syntax.
$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}
You can check string length with strlen. A trim can be additionally used to remove white spece search also.
$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$hasResult = true ; //mark result found
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='articleItem'>
<h2>" . $row['title'] . "</h2>
<p>" . $row['abstract'] . "</p>
<a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
</div>";
}
}
}
if( ! $hasResult ) { //Move to a common section
echo "There are no results matching your search.";
}
Use the below function to get the query string
<?php
$arr_with_index['title'] = $_POST['search'];
$search_qry = getLikeSearchQuery($arr_with_index)
// Add this $search_qry in your query string. This help you to searc N number of values
// For Array and Equal values
function getSearchQuery($arr_with_index) {
$search_qry = "";
if(isset($arr_with_index)){
foreach(#$arr_with_index as $index => $value) {
if(is_array($value)) {
if( implode("",$value) != '' ) {
if($index && $value) { $search_qry .= " and $index IN ('".implode("','",$value)."') "; }
}
} else {
$value = trim($value);
if($index && $value) { $search_qry .= " and "; $search_qry .= " $index = \"$value\" "; }
}
}
}
return $search_qry;
}
// For String
function getLikeSearchQuery($arr_with_index) {
$search_qry = "";
foreach($arr_with_index as $index => $value) {
$inner_flag = false;
if($index && $value) {
$field_arr = explode(",", $index);
foreach($field_arr as $field_index => $field_value) {
if(!$inner_flag) { $search_qry .= " and ( "; } else { $search_qry .= " or "; }
$value = trim($value);
$search_qry .= " $field_value like "; $search_qry .= " \"%$value%\" ";
$inner_flag = true;
}
}
if($inner_flag) { $search_qry .= " ) "; }
}
return $search_qry;
}
?>
I have separate question really which I need help. I only want to display say 20 characters from 'content'.
<?php
$output = '';
if(isset($_GET['q']) && $_GET['q'] !== ' ') {
$searchq = $_GET['q'];
$q = mysqli_query($db, "SELECT * FROM article WHERE title LIKE '%$searchq%' OR content LIKE '%$searchq%'") or die(mysqli_error());
$c = mysqli_num_rows($q);
if($c == 0) {
$output = 'No search results for <strong>"' . $searchq . '"</strong>';
} else {
while($row = mysqli_fetch_array($q)) {
$id = $row['id'];
$title = $row ['title'];
$content = $row ['content'];
$output .= '<a href="article.php?id=' .$id. '">
<h3>'.$title.'</h3></a>'.$content.'';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($db);
?>
i will answer your first question:
insert this line after:
$content = $row ['content'];
if(strlen($content)>20) $content=substr ($content,0,19);
I am a completely newbie in programming php I would like to make this code below return many arrays(to flash as3), however I only receive one array.Can anyone please pinpoint what is my mistake here? thanks.
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
echo "returnStr=$data_array";
exit();
}
When you write your exit insight your loop you stop executing your program and you get only one record. You should set the echo and exit after your while loop.
$data_array = "";
$i = 0;
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql)) {
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1) {
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
} else {
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
Those two last line of your should be outside of your loop:
$data_array = "";
$i = 0;
//if(isset($_POST['myrequest']) && $_POST['myrequest'] == "get_characters")
//{
$sql = mysqli_query($conn, "SELECT * FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql))
{
$i++;
$fb_name = $row["Username"];
$fb_id = $row["Fb_id"];
$fb_at = $row["Access_token"];
$fb_sig = $row["Fb_sig"];
$char_id = $row["Char_id"];
if($i == 1)
{
$data_array .= "$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
else
{
$data_array .= "(||)$fb_name|$fb_id|$fb_at|$fb_sig|$char_id";
}
}
echo "returnStr=$data_array";
exit();
If you would name the columns that you want in the SELECT then it's much simpler. Make sure to use MYSQLI_ASSOC in the fetch:
$sql = mysqli_query($conn, "SELECT Username, Fb_id, Access_token, Fb_sig, Char_id FROM ns_users ORDER BY Char_id");
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC))
{
$data_array[] = implode('|', $row);
}
echo "returnStr=" . implode('(||)', $data_array);
exit();
The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>
1) I want to save case 1 value to an array. Return this array and pass it to a function. The code become case 2, but no result come out, where is the problem?
2) In function display_urls, i want to echo both $url and $category. What should i do in IF condition or add another line of code?
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url."";
echo "".$category."";
}
}
echo "";
}
case 1: work fine
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$i=0;
echo "";
while( $row = oci_fetch_array($result) ){
$i++;
echo "";
echo "".$row['USERNAME']."";
echo "".$row['BM_URL']."";
echo "".$row['CATEGORY']."";
echo "";
}
echo "";
case 2:
$url_array = array();
while( $row2 = oci_fetch_array($result, OCI_BOTH)){
$i++;
$url_array[$count] = $row[0];
}
return $url_array;
I think you probably want something like this:
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url['BM_URL']."";
echo "".$url['CATEGORY']."";
}
}
echo "";
}
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$url_array = array();
while( $row = oci_fetch_array($result, OCI_ASSOC)){
$url_array[] = $row;
}
display_urls($url_array);
This will store all the information on the URLs in $url_array with a lookup by column name.