i passed an array to another page using session
i also passed an index of array
now i want to access that particular index but i am not able to do so can anybody help
here is he first page where i have created the array and stored it in session
<?php
//connection made
$con = mysqli_connect("localhost", "root", "", "QSTNS");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//-----------------two variables entered in datavbase------------
$user = mysqli_real_escape_string($con, $_POST['user']);
$user1 = mysqli_real_escape_string($con, $_POST['user1']);
$sql = "INSERT INTO student (name,rln,scr)VALUES ('$user1','$user','0')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
$res = mysqli_query($con, 'SELECT COUNT(*) FROM qstns');
$row = mysqli_fetch_array($res);
echo $row[0];
$size = $row[0];
//creating an array of size equal to number of questions in DATABASE....
$q_indx = array(); //question indexes without permutation
$attmpt = array(); //check if a question attempted or not
$score = array(); //score per question initially empty
for ($i = 0; $i < $size; $i++) {
array_push($q_indx, $i);
array_push($attmpt, -1);
array_push($score, 0);
}
$cindx = 0;
session_start();
$_SESSION['q_indx'] = $q_indx; //HERE THAT SESSION IS CREATED
$_SESSION['attmpt'] = $attmpt;
$_SESSION['score'] = $score;
$_SESSION['cindx'] = $cindx;
header('Location: quiz_start.php');
mysqli_close($con);
?>
here is the quiz_start.php
<?php
session_start();
$con=mysqli_connect("localhost","root","","QSTNS");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dslpy=$_SESSION['q_indx'][$_SESSION['cindx']] ;
echo $dsply ;
//$qstn = mysqli_query($con,"SELECT * FROM qstns where qid = '". $dsply[0]
."'");
//echo $qstn['qname'] . '\n';
mysqli_close($con);
?>
it is giving error dsply variable not found
can any body help ?
From this script, we can gather that $_SESSION['q_indx'] holds an array of numbers, as below;
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
From your code, $cindx = 0;, so we are looking at index 0. Therefore,
echo $_SESSION['q_indx'][0]; //One way of doing it
echo $_SESSION['q_indx'][$cindx]; //Another way of doing it
EDIT
Cannot use object of type mysqli_result as array in C:\wamp\www\quiiz_portal\quiz_start.php on line 12 can u tell why it there
Change your MySQL query to become
$qstn = mysqli_query($con, "SELECT * FROM qstns where qid = '". $dsply[0] ."'");
EDIT
You are missing session_start(); from your first file.
Related
So I have a SQL database with a number of objects in that contain name price and images, I would like to know how I can select them using php and output the result into json
<?php
$db = mysqli_connect ('localhost', 'root', '', 'car_rental') or die ("SQL is Off");
$car = (isset($_GET['car']) ? $_GET['car'] : null);
mysqli_select_db($db,"car_rental");
$SQL = "SELECT * FROM `products` WHERE name LIKE \'%$car%\'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['sku'] . "<BR>";
print $db_field['name'] . "<BR>";
print $db_field['img'] . "<BR>";
print $db_field['price'] . "<BR>";
}
?>
This is my current code car variable will change dependent on car selected
thanks
For getting all values in json format, you need to use like that:
<?
$newArr = array();
while ( $db_field = mysql_fetch_assoc($result) ) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
?>
UPDATE 1:
You are mixing mysqli extension with mysql. Change mysql into mysqli
UPDATE 2:
Why are you connecting database twice in code?
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "car_rental");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$car = (isset($_GET['car']) ? $_GET['car'] : null);
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
if ($result = mysqli_query($link, $query)) {
$newArr = array();
/* fetch associative array */
while ($db_field = mysqli_fetch_assoc($result)) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
}
?>
Side Note:
Also on PHP error reporting in development phase for saving your time.
I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?
The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?
It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);
You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>
I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way:
$aSpam= array
( '.info'=> 'i'
, 'anal'=> 'i'
, 'anus'=> 'i'
, 'arse'=> 'i'
)
I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php
with the following PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT `SpamWord` FROM spamWords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0;
while($row = $result->fetch_assoc()) {
if($counter){
echo ", '" . $row["SpamWord"]. "'=> 'i'";
$counter++;
} else {
echo "'" . $row["SpamWord"]. "'=> 'i'";
$counter++;
}
}
} else {
echo "Error!";
}
$conn->close();
?>
I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys.
Edit
For example I tried with this solution, but it didn't work:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['SpamWord'] = $row['SpamWord'];
}
foreach($new_array as $array)
{
echo $array['SpamWord'].'<br />';
}
Thank you all in advance,
Denis Saidov
Try like below:-
$sql = "SELECT `SpamWord` FROM spamWords";
$result = mysqli_query($conn ,$sql) or die(mysqli_error($conn));
$resultArray = array(); // create an array
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$resultArray[$row["SpamWord"]] = 'i'; // assing value
}
} else {
echo "Error!";
}
echo "<pre/>";print_r($resultArray); // print array
$conn->close();
Note: Here you will get your original array containing all SpamWord values comes from database.thanks
PHP array's are like dictionnaries (a list of key/value pairs)
First, before your loop, create your array empty:
$new_array = Array();
while...
Then for each column, you append the column value as a new key for the array
$new_array[$row['SpamWord']] = "i";
As in your example, I put "i" as the value for each array's row.
Hi I'm starting out on php and I have the following script
<?php
$username = "firstleg_floa";
$password = "**";
$hostname = "***1";
$db = "firstleg_bank";
$guildUser = strtolower('grissiom');
$dbh = mysql_connect( $hostname, $username, $password) or die ("Unable To Connect");
$connectDB = mysql_select_db($db, $dbh);
$results = mysql_query("SELECT * FROM Bank where userId ='" .$guildUser."'");
$i = 0;
$rsArr = array();
While ($row = mysql_fetch_array($results, MYSQL_ASSOC))
{
$rsArr [$i] [0] = $row{'userId'};
$rsArr [$i] [1] = $row{'item'};
$rsArr [$i] [2] = $row{'amount'};
$rsArr [$i] [3] = $row{'position'};
$i++;
}
?>
<?="ghdfdgdfg ". $rsArr[$i][1];}." ----";?>
<? echo $rsArr[$i][0]; ?>
<table>
<tr><td>Item</td><td>Amount</td></tr>
<?for ($x=0;$x <= $i; $x++)
{?>
<tr><td><?=$rsArr[$x][3];?></td><td><?=$rsArr[$x][2];?></td></tr>
<?}?>
</table>
<?php
mysql_close($dbh); ?>
and I have the following data in the database
1 - grissiom - Silk Cloth - 100 - 1
with the above data and the above script all I can manage to pull out is the amount(100) and the position(1) how come i am unable to pull anything else out? can someone help me please
It could be because you're using curly braces instead of square. The row returned by mysql_fetch_array() is a PHP array, not an object or string.
Possible solutions:
1) Those column names in the DB have different case, e.g. userId could be just userid
2) Those columns don't exist.
3) You are using curly braces, instead of square brackets:
$rsArr [$i][0] = $row{'userId'}; //wrong
$rsArr [$i] [0] = $row['userId']; //correct
Try replacing the while loop with this, it will read out the contents of each record as the DB has passed it to PHP:
while ($row = mysql_fetch_array($results, MYSQL_ASSOC))
{
echo '<pre>' . var_dump($row) . </pre>;
}
to see exactly what is coming back from the DB.
after loop is finished $i is equal to 1, but $rsArr[$i] is not defined, so variables $rsArr[$i][0] and $rsArr[$i][1] doensn't exists, try using $rsArr[0][0] and $rsArr[0][1] like this:
<?="ghdfdgdfg ". $rsArr[0][1];}." ----";?>
<? echo $rsArr[0][0]; ?>
<table>
<tr><td>Item</td><td>Amount</td></tr>
<?for ($x=0;$x <= $i; $x++)
{?>
<tr><td><?=$rsArr[$x][3];?></td><td><?=$rsArr[$x][2];?></td></tr>
<?}?>
</table>
It seem ok to me, maybe issue is given from using curly braces.
Anyway i'd go with some simpler syntax, i.e:
<?php
$username = "firstleg_floa";
$password = "**";
$hostname = "***1";
$db = "firstleg_bank";
$guildUser = strtolower('grissiom');
$dbh = mysql_connect( $hostname, $username, $password) or die ("Unable To Connect");
$connectDB = mysql_select_db($db, $dbh);
$results = mysql_query("SELECT * FROM Bank where userId ='" .$guildUser."'");
$i = 0;
$rsArr = array();
while ($row = mysql_fetch_array($results, MYSQL_ASSOC))
{
$rsArr[] = $row;
}
mysql_close($dbh);
echo '<table><tr><td>Item</td><td>Amount</td></tr>';
for ($i = 0;$i<count($rsArr);$i++){
echo <<<EOF
<tr><td>{$rsArr["item"]}</td><td>{$rsArr["amount"]}</td></tr>
EOF;
}
echo '</table>';
?>