Undefined variable while fetching data from mysqli - php

I'm new to php n I'm trying to make a phone to timezone converter.
I'm getting the error undefined variable '$result' on line 49
How do I resolve it.
Also if you can find out any other mistakes I've made
Please chck for errors I'm making
Phone number:
<button type="submit" name="submit" action="submit">
Submit
</button>
</form>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$ccode=$_POST["phone"];
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$pattern = '/^\(?[\d]{1,4}\)?( |-)?/';
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else $code = substr($ccode, 0, 4);
$q = "SELECT nicename FROM country.country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($record);
if (empty($_POST["phone"]))
{
echo "<p>Please write a Phone Number!</p>";
}
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = " . $record['nicename'];
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($result);
?>
</body>
Thanks for the help!

I believe this way it will works. I'm not sure about $code, if he contains the right information, you can check that by echo'ing the $code.
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else { $code = substr($ccode, 0, 4); }
$q = "SELECT nicename FROM country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
echo '<pre>';
print_r($record);
} else { echo "<br/>NO RECORD"; }
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = '" . $record['nicename'] . "'";
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
echo '<pre>';
print_r($result);
//Here $result will exist!
} else { echo "<br/>NO RECORD"; }
// You had your $result here, and here, the result may not exist,
// depending if the query succeeded or not.
// Same counts for the query above.
There were 2 problems as far as I can tell.
1 was that you tried to print $record, while $record may not have existed, and the same counts for $result.
2 was the zone-query, if you check if a column/field equals a certain string, then make sure the string has quotes around itself. So country_name='something'. You didn't have these quotes around $record['nicename'], so whatever came out of $record['nicename'], he thought it was a column/field, but not a value to check upon.

Related

About the error of PHP-Column count doesn't match value count at row 1

I'm new about the PHP. I create a login form and after I fill up all the input fields. I clicked "SUBMIT" and then it says.. "Column count doesn't match value count at row 1". anybody help me about this. I'm stack with this almost 1 week.. here is my code. and my db connection.
<?php
$connection = mysqli_connect("localhost","root","","db_violation");
function DBCon(){
try{
$connection = new PDO("mysql:host=localhost;port=3306;dbname=db_violation;","root","");
return $connection;
}catch(PDOException $e){echo "Connection failed: ".$e->getMessage();}
}function DBDiscon(){return $connection = null;}
?>
<?php
include '../../PROCESS/dbconnect/dbconnect.php';
$datauserssystems = json_decode(file_get_contents("php://input"));
$user_firstname = mysqli_real_escape_string($connection, $datauserssystems->user_fname);
$user_middlename = mysqli_real_escape_string($connection, $datauserssystems->user_mname);
$user_lastname = mysqli_real_escape_string($connection, $datauserssystems->user_lname);
$user_address = mysqli_real_escape_string($connection, $datauserssystems->user_address);
$user_positionss = mysqli_real_escape_string($connection, $datauserssystems->user_positions);
$user_age = mysqli_real_escape_string($connection, $datauserssystems->user_age);
$user_username = mysqli_real_escape_string($connection, $datauserssystems->user_uname);
$user_userpass = mysqli_real_escape_string($connection, $datauserssystems->user_pwd);
$tableRows = DBCon()->prepare("SELECT COUNT (*) AS row FROM sb_account");
$tableRows->execute();
$count = $tableRows->fetch();
$count = ($count["row"]+1);
$gain ="SbAdmin";
$encrpt = md5($gain.$user_userpass);
$security = DBCon()->prepare("INSERT INTO sb_account_security VALUES('".$count."','".$encrpt."','".$user_userpass."')")->execute();
$sbuserssssquery = mysqli_query($connection, "SELECT * FROM sb_account WHERE sb_username='$user_username'");
$sbuserssssarray = mysqli_fetch_array($sbuserssssquery);
$sbuserssss = $sbuserssssarray['sb_username'];
if($sbuserssss == $user_username) {
echo "sbtwice";
die();
}
else {
mysqli_query($connection, "INSERT INTO sb_account (sb_firstname,sb_middlename,sb_lastname,sb_fullname,sb_address,sb_position,sb_age,sb_username,sb_password) VALUES ('$user_firstname','$user_middlename','$user_lastname','$user_address','$user_positionss','$user_age','$user_username','$encrpt')");
if(mysqli_affected_rows($connection) > 0) {
echo "AddUserSystem";
die();
}
else {
echo mysqli_error($connection);
die();
}
}
?>
Your mysql insert query has issue:
INSERT INTO sb_account
(sb_firstname,
sb_middlename,
sb_lastname,
sb_fullname,
sb_address,
sb_position,
sb_age,
sb_username,
sb_password)
VALUES ('$user_firstname',
'$user_middlename',
'$user_lastname',
'$user_address',
'$user_positionss',
'$user_age',
'$user_username',
'$encrpt');
Here you have 9 columns but are supplying 8 values. You are not passing value for sb_fullname column.

PHP MySQLi if ID = 1 echo name from row

I'm trying to make something which will only display the name of the row which has ID 1 but I can't seem to get it to work. I can make it display all the names but I only want it to display the name of user ID 1. This is my current code but it doesn't work.
<a style="font-size: 17px; color: #ff0000;"><?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result=mysqli_query($q);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row != FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo $name;
} else{echo "it's false :(";};
?></a>
It returns:
it's false :(
you may need the while() check on there.
Try something like:
Your database connection:
$servername = "YOUR_HOST";
$username = "YOUR_USER";
$password = "YOUR_PASSWORD";
$dbname = "YOUR_DATABASE";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then your main file with displaying the row you want:
// create query
$q = "SELECT * FROM Team WHERE id = 1";
// get the records from the database
if ($result = $mysqli->query($q))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// fetch the results
while ($row = $result->fetch_object())
{
$name = $row->name;
echo $name;
}
}
else
{
echo "No results to display!<br><hr><br>";
}
}
else
{ // show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
mysqli_query requires first parameter should be connection string and second is the query
mysqli_query($link, "your query");
Ref: http://php.net/manual/en/mysqli.query.php
You need to add the Connection-Parameter!
$result=mysqli_query($db, $q);
instead of
$result=mysqli_query($q);

Using preg_match on array from POST checkbox values

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";
}
?>

How do I retrieve a single row from a table using PHP?

I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();

No connection could be made

No connection could be made because the target machine actively refused it.
Here is my code.
//$db = 'htdocs\as4.mdb';
//$conn = new COM('ADODB.Connection');
mysql_connect('htdocs\as4.mdb');
mysql_select_db('vendor');
$search = $_POST['search'];
$sql = "SELECT * FROM vendor WHERE vendorName like '%search%' OR
address like '%search%' or
city like '%search%' or
provState like '%search%' or
country like '%search%'";
$result = mysql_query($sql, $conn) or die (mysql_error());
$number = mysql_num_rows($result);
// <h3>$number of results found search for "$search"</h3>
while($row = mysql_fetch_array($result))
{
$vendorName = $row['vendorName'];
$address = $row['address'];
$city = $row['city'];
$provState = $row['provState'];
$country = $row['country'];
}
?>
I'm trying to connect to the database and through a search textbox find a certain keyword and display results with anything that has to do with the key word, for example if I type in Canada I would like to see the results of all the people in Canada. I tried to do it through new COM('ADODB.Connection') as you can see it commented out, but couldn't figure out exactly how.
What if I wanted to use something like this to search the database?
$db = 'htdocs\database\database.mdb';
$sql = "SELECT * FROM Vendor";
//to make this work, you need to add
//extension=php_com_dotnet.dll
//to your php.ini file. Put it with the other
//extension=
//values towards the bottom of the file (around line number 1050)
$conn = new COM('ADODB.Connection');
if(!$conn)
{
echo "Database unreachable";
exit();
}
else
{
echo "Success!<hr />";
try
{
$conn -> Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db");
$rs = $conn->Execute($sql);
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "<br />";
exit();
}
while(!$rs->EOF)
{
For($i = 0; $i < ($rs->Fields->Count); $i++)
{
echo $rs->Fields[$i]->Value;
echo " ";
}
echo "<br />";
$rs->MoveNext();
}

Categories