PDA

View Full Version : basic connection


tony09uk
08-19-2012, 09:22 PM
Hi, I am having an issue with basic connections with mysqli. I have added my code below and below that the output. Why does it show the information twice?
If I remove the foreach loop, I just get ArrayArrayArray. If I remove the while loop I get nothing.

I have searched around on the net but cant find anything that shows how to connect to mysqli, the procedural way. I am trying not to move onto oop yet until I can work with databases correctly.

$connection = mysqli_connect('localhost', 'user', 'password', 'test');
$query = 'SELECT * FROM cars';
$result = mysqli_query($connection, $query, MYSQLI_USE_RESULT);


while($row = mysqli_fetch_array($result)){

foreach($row AS $value){
echo $value . "<br/>";
}

}

//result
1
1
SLK
SLK
MERC
MERC
CAR
CAR
2
2
GTI
GTI
MITSUBISHI
MITSUBISHI
CAR
CAR

tony09uk
08-19-2012, 09:53 PM
So this works

$connection = mysqli_connect('localhost', 'root', 'penbird098', 'test');
$query = 'SELECT * FROM cameras';
$result = mysqli_query($connection, $query, MYSQLI_USE_RESULT);


while($row = mysqli_fetch_array($result)){


echo $row[0] . $row[1] . $row[2] . "<br/>";


}

but i am aiming to achieve this result dynamically.

edbr
08-21-2012, 01:47 AM
here is a PDO connection to mysqli give this a try

PDO connection
<?php
/*** hostname ***/
$hostname = 'localhost';
/*** username ***/
$username = 'vvvvv';

/*** mysql password ***/
$password = 'vvvvv';
function testdb_connect ()
{
$dbh = new PDO("mysqli:host=$hostname;dbname=scripts", 'test' , 'edbypass');
return ($dbh);
}
?>
$sql = "SELECT * FROM table;

foreach ( $dbh->query($sql) as $row) {
echo $row['category'];
}

include file then

tony09uk
08-21-2012, 09:00 PM
ive found a number of tutorials that show how connect to mysqli using oo. But i dont understand oo yet so i didnt want to mix procedural and oo as intend on learning oo later once i have a stronger understanding

edbr
08-22-2012, 01:09 AM
pdo is not really complete OOP, as a connection it can be used for many type off databases including mysql with added sfety from injection. You can fetch array,associate or object if you want

jmichae3
09-01-2012, 07:53 AM
one thing you need to do is use mysqli_free_result($result); at the end of your script. script won't work right according to docs without it.