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();
?>
Related
<?php
$mysqli = new mysqli("localhost", "root", "", "titan3d");
if (mysqli_connect_error()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sdate = "";
$stime = "";
if(isset($_POST['sdate']))
{
$sdate = $_POST["sdate"];
}
if(isset($_POST['stime']))
{
$stime = $_POST["stime"];
}
$statement = $mysqli->prepare("SELECT bookedseat FROM bookings WHERE sdate = ? AND stime = ?");{
$statement->bind_param("si", $sdate, $stime);
if (!$statement->execute()) {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement->bind_result($book);
$statement->fetch();
printf($book);
//header('Location: http://localhost/My%20Project/seats.html');
$statement->close();
}
$mysqli->close();
?>
This is my php file made to get the data from a form and make a query and then display the results.
When executed,the php works perfectly.
But it only displays the first value in the query.
Why is it?
How can I display all the values in my query?
You need to use $stmt->fetch() in a while loop, you can then iterate over each the returned row.
while ($stmt->fetch()) {
// $book will have the value of bookedseat for the current row
}
I can't figure out how to load the mySQL results (address,name) into this format:
$to=array(
array("address"=>"johndoe#domain.ext","name"=>"John Doe"),
array("address"=>"jofrost#domain.ext","name"=>"Jo Frost"),
array("address"=>"someone#domain.ext","name"=>"Some One"),
etc...
);
Please the old way for learning.
Thx.
like that
$query = 'SELECT address, name FROM table';
$mysqli = new mysqli('host', 'user', 'password', 'database');
if ($mysqli->connect_errno) {
echo 'Connect failed:' . $mysqli->connect_error;
exit();
}
if($res = $mysqli->query($query)) {
$ret = [];
while($row = $res->fetch_assoc()) {
$ret[] = $row;
}
print_r($ret);
} else {
echo $mysqli->error;
}
see more:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli-result.fetch-assoc.php
I want to print result of a Mysqli query, But when I try to do as following way, It does not return any values or error. The code does not go through the while loop. What would be the wrong with my code, Please help me!
<?php
$mysqli = new mysqli("localhost", "root", "", "domains");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$part = explode(".", $str);
$part1 = $part[0];
$part2 = $part[1];
$sql = "SELECT
DomainCategory.Name
FROM
DomainName_Client,
DomainNameType,
DomainCategory,
OrderDomain_Client
WHERE
DomainName_Client.Name = '$part1'
AND DomainNameType.Name = '$part2'
AND DomainName_Client.TypeID = DomainNameType.ID
AND DomainCategory.ID = DomainName_Client.DomainCategoryID
AND OrderDomain_Client.DomainNameID = DomainName_Client.ID";
$result = $mysqli->query($sql);
if (!$result = $mysqli->query($sql)) {
die('There was an error running the query ' . $mysqli->error . ']');
}
while ($row = $result->fetch_assoc()) {
echo 'Total results: ' . $result->num_rows;
}
?>
First you check the number of results returning in the sql query using the following code and after that you print it using while or for loop.
echo $result->num_rows;
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.
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;
}
}