This is my first post so please bear with me with inputting the code into here. Im trying to output some images to a PDF and need to create a if statement that looks for data with in a row.
$connection = mysql_connect("localhost", "testdb", "********")
or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result)) {
$image = $row[1];
$text = $row[2];
}
That's what I have so far and basically I need something along the line of this:
If (data in row 1) {
print $image;
} else {
print $text;
}
It's hard to say exactly what you're looking for since it isn't very clear, but I think what you're wanting to do is check to see if $image has a value, and if so, display it. If not, display $text instead.
If this is the case use empty(). It will tell you if a variable is empty or not.
if (!empty($image))
{
print $image;
}
else
{
print $text;
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
looks like you just need to test for data in $image
if(!empty($image))
{
echo $image;
}
else
{
echo $text;
}
if( !empty($row[1]) ) {
...
Use isset to check variable.
Like
if(isset($images) !='')
{
echo $images;
}
Although you are using old mysql_* functions which are depreciated, you are almost there
$connection = mysql_connect("localhost", "testdb", "********") or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result))
// This will only be called if there is a matching result.
{
echo $row[1];
echo $row[2];
}
Edit: Here is a cut and paste of a section of a query that happen to be open in eclipse:
$arrKPIData = Array();
try{
$dbh = new PDO($this->mySQLAccessData->hostname, $this->mySQLAccessData->username, $this->mySQLAccessData->password);
$stmt = $dbh->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new kpiData);
$dataCount=0;
foreach($stmt as $kpiData)
{
$arrKPIData[$dataCount]['year']=$kpiData->year;
$arrKPIData[$dataCount]['month']=$kpiData->month;
$arrKPIData[$dataCount]['measure']=$kpiData->kpiMeasure;
$arrKPIData[$dataCount]['var1']=$kpiData->var1;
$arrKPIData[$dataCount]['var2']=$kpiData->var2;
$dataCount++;
unset($stmt);
}
unset($dbh);
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
unset($arrKPIData);
I am populating a simple array with data before I cleanse it and convert it into a class further in the code.
Related
Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}
I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.
I have tried the following code to output each student father_contact by firstly merging them and secondly separating each number by comma and could not make it working. Please help me.
$sql = "SELECT Fathers_Contact FROM student WHERE Class ='$class' AND Section='$s' and Year='$y'";
$result = mysql_query($sql);
if (!$result) {
die("Query not working");
}
$mbno_arr = array();
while ($row = mysql_fetch_array($result)) {
$mbno_arr[] = $row[0];
}
$mbno_list = implode(',', $mbno_arr);//expect here is: 9867656543,9867656443,9867654543
if(empty($mbno_list)){
echo "No number is there";
exit;
}
if(empty($msg)){
echo "Message empty!";
exit;
}
Father_contact is ten digit mobile no.
// Escapes special characters in a string for use in an SQL statement
$SQL = sprintf(
"SELECT Fathers_Contact
FROM student
WHERE Class = '%s' AND Section = '%s' and Year = '%s'",
mysql_real_escape_string($class),
mysql_real_escape_string($s),
mysql_real_escape_string($y)
);
// Result or die (print mysql error)
$result = mysql_query($SQL) or die( mysql_error() );
// Check if result has rows
if( mysql_numrows($result) > 0 )
{
$mbno_arr = array();
while ( $row = mysql_fetch_array($result) )
$mbno_arr[] = $row[0];
if( count($mbno_arr) > 0)
echo implode(',', $mbno_arr);
else
echo 'No number is there';
}
else
{
echo 'No result for query';
}
// free result
mysql_free_result($result);
NB use PDO or mysqli. mysql_* is deprecated
Firstly, mysql_* is now officially deprecated. Please use PDO or MySQLi.
Can you try this:
<?php
// Connect
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query
$query = "SELECT Fathers_Contact FROM student WHERE Class = ? AND Section = ? and Year = ?";
if ($stmt = $mysqli->prepare($query)) {
{
// Bind params
$stmt->bind_param("sss",
$class,
$s,
$y);
// Execute statement
$stmt->execute();
// fetch associative array
$mbno_arr = array();
$result = $stmt->fetch_result();
while ($row = $result->fetch_assoc())
{
// Build data
$mbno_arr[] = $row['Fathers_Contact'];
}
// close statement
$stmt->close();
// Debug?
$mbno_list = implode(',', $mbno_arr);
if (empty($mbno_list)) {
echo "No number is there";
} else {
echo "Query Results: $mbno_list";
}
}
// Close Connection
$mysqli->close();
?>
I'm very new to PHP and still learning the basics and I'm stuck on an issue I'm hoping someone could help me with.
I have the following code;
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
if($MfgQueryRun = mysql_query($MfgQuery)) {
if (mysql_num_rows($MfgQueryRun)==NULL){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
} else {
echo 'Query Unsuccessful';
}
But for a reason unknown to me I keep getting 'No Mfg Results Returned' but if I copy and paste the query by itself into the MySQL box in PHPMyAdmin it returns a result properly.
What gives??
BTW, Here's exactly what I can insert into PHP MyAdmin's SQL box;
SELECT `Mfg` FROM `categories` WHERE `ID` = 10
and this returns a result but using the code above, it does not.
If anyone wouldn't mind showing me where I went wrong I'd be most appreciative and I thank you in advance
try this
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
$MfgQueryRun = mysql_query($MfgQuery) ;
$row = mysql_fetch_array($MfgQueryRun) ;
if (mysql_num_rows($MfgQueryRun)== 0 ){
echo 'No Mfg Results Returned';
} else {
$Mfg = $row['Mfg'];
echo $Mfg;
}
Try
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
$MfgQueryRun = mysql_query($MfgQuery);
if($MfgQueryRun) {
if (mysql_num_rows($MfgQueryRun) == 0){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
} else {
echo 'Query Unsuccessful';
}
if (mysql_num_rows($MfgQueryRun)){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
Try this remove the NULL in comparison. because mysql_num_rows returns numeric values.
First, you should not use mysql_* functions, they are deprecated (outdated) as of PHP 5.5.0, and will be removed in the future. Use mysqli instead.
Second, you're not testing properly. PHP has no strong types, so a test '== null' does not always do, what you'll expect. See the PHP manual for comparision operators. To test against null, always use is_null().
Third, you're not fetching the data.
Using MySQLi, the code would look similar to this:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno != 0) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
die(); // or return, if in method or function context
}
$result = $mysqli->query("SELECT `Mfg` FROM `categories` WHERE `ID` = 10");
if ($result === false) {
echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
die(); // or return, if in method or function context
}
printf("Select returned %d rows.\n", $result->num_rows);
$row = $result->fetch_assoc();
echo $row['Msg'];
/* free result set */
$result->close();
I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}