PHP: Unable to run same MySQL query several times - php

HTML FILE:
<form method="post" action="generate.php">
Product Reference(s): (if multiple, separate by ",")<br />
<input type="text" name="project_ref" value="REF123, REF124" />
<input type="submit" value="Generate" />
</form>
PHP FILE:
<?php
$ref_array = explode(',', $_POST['project_ref']);
foreach ($ref_array as &$ref) {
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference = '$ref' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
RESULTS:
Brand: Bose
0 results
But I actually wanted:
Brand: Bose
Brand: Beats
So the problem is that the MySQL query is not running for every array item. Its only executing the first item of the array.

Your input value has a space between the different refs: REF123, REF124
You can either explode on a comma & space:
$ref_array = explode(', ', $_POST['project_ref']);
Or trim the values:
$sql = "SELECT * FROM `inventory` WHERE reference = '" . trim($ref) . "' LIMIT 1";
It's also strongly recommended that you pass in $ref as a parameter, rather than a string literal:
http://php.net/manual/en/mysqli-stmt.bind-param.php

It looks like your issue is in your explode. The first value of the explode is correct the second (third, forth, etc.) will have a leading space. explode on ', ' instead of ',' or trim the results before using it.
But there are a few other things in this code. Don't create a new connection for each query, the single connection will work just reuse it. Second, use parameters or sanitize the value before you use it in the sql, this will help prevent sql injection attacks, a better way is to use PDO and use parameters. Last, change your query so that a single query returns all the results you need by using an IN clause.
<?php
$ref_array = explode(', ', $_POST['project_ref']);
$ref_IN = "";
foreach ($ref_array as $ref_val)
$ref_IN .= "'{$ref_val}', ";
$ref_IN = rtrim($ref_IN , ",");
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference IN ({$ref_IN}) GROUP BY reference";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Related

What is the correct MySQL database statement where the variable defined as all the rows

I try to explain this well folks,
I have a database with 20 questions with two principles : 1) Cardiology and 2) Endocrine. And you can select using HTML selection menu either of the concepts or you can select 3) All.
And on my html page I have a selection menu with 3 options and they each have a value:
<div id="selectContainer1">
<select id="selectedPrinciple" name="selectedPrinciple">
<option value="" disabled="disabled" selected="selected">Select a System</option>
<option value="">All</option>
<option value="VASCULAR">Cardiology, Vascular System</option>
<option value="ENDOCRINE">Endocrine</option>
</select>
</div>
<input type="submit" value="Start">
I have this code on php:
$selectedPrinciple = $_POST['selectedPrinciple'];
$sql = ("SELECT * FROM qbanktable WHERE Principle = '$selectedPrinciple'"
Now when I select option "Cardiology" or "Endocrine", all the rows that are related to those are picked from my database and showed on the next page. But when I select "All" I get a syntax error because of course as it does have no value the row cannot be found on my database. Is there anything I can put for the option value for "All" that the mysql returns all the rows?
You could check if $selectedPrinciple is empty() and modify the query accordingly.
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// this line indicates that you don't use prepared statements
$sql = "SELECT * FROM `qbanktable` WHERE `Principle` = '$selectedPrinciple'";
} else {
$sql = "SELECT * FROM `qbanktable`";
}
full example using mysqli prepared statement
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `qbanktable` WHERE `Principle` = ?");
$stmt->bind_param("s", $selectedPrinciple);
} else {
// prepare
$stmt = $conn->prepare("SELECT * FROM `qbanktable`");
}
// execute
$stmt->execute();
// fetch data
if (!($res = $stmt->get_result())) {
echo "Failed to fetch the result set: (" . $stmt->errno . ") " . $stmt->error;
}
// print data
print_r($res->fetch_all());
// close prepared statement
$stmt->close();
// close connection
$conn->close();
Personally, I like to use a few techniques to "build" my query, like so:
NOTE:
I'm demonstrating how to do this with PDO and parameter binding, because your query is open to SQL injection attacks.
$sql = "SELECT * FROM `qbanktable`";
$where = [];
$params = [];
if ( ! empty( $_POST['selectedPrinciple'] ) ) {
$where[] = '`Principle` = ?';
$params[] = $_POST['selectedPrinciple'];
}
if ( /* some other condition */ ) {
// add to the $where / $params as appropriate
}
// Glue the $where into a string
$where = implode( ' AND ', $where );
// Append where to the $sql statement
$sql .= ( $where ) ? ' WHERE ' . $where : '';
// assumes $conn is already a set-up PDO connection
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
I think the best way is to check in PHP if the value of selectedPrinciple is something like ALL or is empty, and then don´t add the WHERE part of the query.
If really want to use some value for All option, you can try to use one or two percents signs '%' or '%%', but I don´t remember if it works. However, I don´t recommend this approach. Take care also about SQL Injection.

Strings differents but equals in php

I am using eclipse editor. I am programming within vtiger 5.4. in my file config.inc.php the variable $default_charset is setted as
$default_charset = 'UTF-8';
I'm trying to make a sql query in mysql using the next variable
$sql = "select cod_dpto from vtiger_ubi where dpto='" . $dpto . "'";
When I print the variable $dpto I get "SAÑA", but the execution of the query mysql
$adb->query ( $sql );
doesn't work. But when I modify my query as:
$sql = "select cod_dpto from vtiger_ubi where dpto='SAÑA'";
the instruction
$adb->query ( $sql );
returns the values that I need.
Could you help me please, how can I convert my variable $dpto such that the sql query works well.
EDIT
I trying to make the query with the below code, without vtiger, and I get 0 results for thw two cases with variable and writing 'SAÑA'
$servername = "localhost";
$username = "root";
$password = "peru2006";
$dbname = "consuladoperurio_com_br_2";
$port = "3306";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname, $port );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "select cod_dpto from vtiger_ubigeo where dpto='$dpto'";
echo $sql;
$result = $conn->query ( $sql );
if ($result->num_rows > 0) {
// output data of each row
while ( $row = $result->fetch_assoc () ) {
echo "id: " . $row ["cod_dpto"] "<br>";
}
} else {
echo "0 results";
}
$conn->close ();
Your Select statement looks like this:
$sql = "select cod_dpto from vtiger_ubi where dpto='".SAÑA."';
you'll probably want it to look like:
$sql = "select cod_dpto from vtiger_ubi where dpto='$dpto'";
Notice no concat operator, and the variable is only wrapped in single quotes.

Mysql table using LIMIT, breaks randomly

When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>

Value returned from mysqli db call in php doesn't return values with newline chara

Ok so for some reason when I try and get values from a cell in my table with type TEXT it returns nothing, even thought there is text in the cell. It might be because there are new line characters in the text. In fact I'm certain that's the reason cause the only time things aren't return from the table is when there are newlines in it.
Here is the code where I get the data from my db:
function getRecord($cmo_name,$username,$password){
$i = 0;
$servername = "localhost";
$db = "my_db";
$return_array[] = "";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `my_table` WHERE `Name` = '".$name."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
foreach($row as $value)
array_push($return_array, $value);}
}
$conn->close();
return $return_array;
}
The above code returns nothing for the TEXT column that includes the newlines.
Help please!!!
Wrap your query result in PHP's TRIM function to strip the newline and returns out:
http://php.net/manual/en/function.trim.php

Script to count two columns and echo result

I have a working SQL query that I'm trying to use in a small PHP script but getting Parse error, tried many variations. Hope you can help. End result would be to have a two field form with 'Date' and 'Channel No' then giving result count of number of 'channel' rows for a given date. Sorry fairly new PHP/SQL, thanks.
<?php
// Connect to MSSQL and select the database
$link = mssql_connect('localhost', 'root', '', 'jm_db');
mssql_select_db('jm_db');
// Select all our records from a table
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
echo $sql;
?>
I have re-done the code but getting 'Warning: mysql_fetch_array() expects parameter 1 to be resource' and undefined variable.
<?php
// Create connection
$mysqli = new mysqli($localhost, $root, $jm_db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
$results= array();
while ($result = mysql_fetch_array($sql)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
?>
You're missing a quote (Stack's syntax highlighting shows you), yet it should be replaced with an opening double quote and ending with the same. You can't use all single quotes.
I replaced the opening single quote with a double, along with a matching closing double quote.
$mysql_query = mssql_query ("SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%'");
As a sidenote, you're echoing the wrong variable.
However, that is not how you would echo out results, but with a loop.
Something like, and replacing Fieldname with the one you want to use:
while ($row = mssql_fetch_assoc($mysql_query)) {
print $row['Fieldname'] . "\n";
}
or use mssql_fetch_array()
You can also use:
$results= array();
while ($result = mssql_fetch_array($mysql_query)) {
$results[]= $result;
}
foreach($results as $result){
echo $result['calldate'] . " " . $result['channel'];
}
For more information on Microsoft SQL Server's function, consult:
http://php.net/manual/en/book.mssql.php
$mysql_query = mssql_query ('SELECT COUNT(*) FROM asterisk_cdr
WHERE calldate LIKE '%2014-10-11%'
AND channel LIKE '%SIP/4546975289%');
while($row=mssql_fetch_array($mysql_query))
{
echo $row[0];
}
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysql_query = mysqli ("SELECT COUNT(*) FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
while ($row = mysql_fetch_array($mysql_query, MYSQL_ASSOC)) {
echo ($row["channel"]);
}
this is a simple example with PDO
<?php
try {
$dns = 'mysql:host=localhost;dbname=jm_db';
$user = 'root';
$pass = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$cnx = new PDO( $dns, $user, $pass, $options );
$select = $cnx->query("SELECT COUNT(*) as count FROM asterisk_cdr WHERE calldate LIKE '%2014-10-11%' AND channel LIKE '%SIP/4546975289%'");
$select->setFetchMode(PDO::FETCH_OBJ);
while( $row = $select->fetch() )
{
echo '<h1>', $row->count , '</h1>';
}
} catch ( Exception $e ) {
echo "Connect failed : ", $e->getMessage();
die();
}

Categories